Skip to main content

如何通过边缘拖动自动滚动舞台?

如何通过边缘拖动自动滚动舞台?

如果你想提升你的 Konva.js 应用程序的用户体验,实现自动滚动功能是一个很好的选择。这一功能在交互式用户界面中特别有用,用户需要拖动项目或浏览大型画布。通过启用滚动,在用户将项目拖动到视口的底部或右侧边缘时自动移动,你可以创建一种更平滑和直观的交互体验。

import Konva from 'konva';

const stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight,
});

const layer = new Konva.Layer();
stage.add(layer);

const NUMBER = 100;

function generateNode() {
return new Konva.Circle({
x: stage.width() * (Math.random() * 2 - 1),
y: stage.height() * (Math.random() * 2 - 1),
radius: 40,
fill: 'red',
stroke: 'black',
draggable: true,
});
}

for (let 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);
});

说明: 开始拖动任何形状。当你将它拖到舞台边缘附近时,舞台将自动向该方向滚动。这创造了一个平滑的无限滚动体验。