If you’re looking to enhance your Konva.js application’s user experience, implementing an auto-scroll feature is a great way to go. This functionality is especially useful in interactive UIs where users need to drag items or navigate large canvases. By enabling the scroll to automatically move when a user drags an item to the bottom or right edge of the viewport, you create a smoother and more intuitive interaction.
Instructions: Start dragging of any shape. Drag it near corder of the stage. Stage will start scrolling.
Scroll By Edge Drag Demo view raw <!DOCTYPE html > <html > <head > <script src ="https://unpkg.com/[email protected] /konva.min.js" > </script > <meta charset ="utf-8" /> <title > Konva Canvas Scrolling Drag Demo</title > <style > body { margin: 0; padding: 0; overflow: hidden; background-color : #f0f0f0 ; } </style > </head > <body > <div id ="container" > </div > <script > var width = window .innerWidth; var height = window .innerHeight; var stage = new Konva.Stage({ container: 'container' , width: width, height: height, }); var layer = new Konva.Layer(); stage.add(layer); var NUMBER = 100 ; function generateNode () { return new Konva.Circle({ x: width * (Math .random() * 2 - 1 ), y: height * (Math .random() * 2 - 1 ), radius: 40, fill: 'red' , stroke: 'black' , draggable: true , }); } for (var i = 0 ; i < NUMBER; i++) { layer.add(generateNode()); } let scrollInterval = null ; stage.on('dragstart' , (e) => { const duration = 1000 / 60 ; scrollInterval = setInterval(() => { const pos = stage.getPointerPosition(); const offset = 100 ; const isNearLeft = pos.x < offset; if (isNearLeft) { stage.x(stage.x() + 2); e.target.x(e.target.x() - 2); } const isNearRight = pos.x > stage.width() - offset; if (isNearRight) { stage.x(stage.x() - 2); e.target.x(e.target.x() + 2); } const isNearTop = pos.y < offset; if (isNearTop) { stage.y(stage.y() + 2); e.target.y(e.target.y() - 2); } const isNearBottom = pos.y > stage.height() - offset; if (isNearBottom) { stage.y(stage.y() - 2); e.target.y(e.target.y() + 2); } }, duration); }); stage.on('dragend' , () => { clearInterval(scrollInterval); }); </script > </body > </html >