如果您希望提升您的 Konva.js 应用程序的用户体验,实现自动滚动功能是一个很好的选择。这个功能在用户需要拖动项目或浏览大型画布的交互式 UI 中尤其有用。通过启用滚动,使用户在将项目拖到视口的底部或右侧边缘时,自动移动画布,您将创建更顺畅、更直观的交互体验。
说明:开始拖动任意形状。将其拖到舞台的角落附近。舞台将开始滚动。
Scroll By Edge Drag Demoview raw<!DOCTYPE html> <html> <head> <script src="https://unpkg.com/konva@9.3.18/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>
|