跳到主要内容

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

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

在 Konva.js 应用中实现自动滚动功能,可以改善用户体验。此功能特别适合需要拖动项目或浏览大型 Canvas 的交互式 UI。当用户把项目拖到视口底部或右侧边缘时,滚动区域会自动移动,从而使交互更加流畅直观。

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);
});

操作说明: 开始拖动任意图形。将图形拖到舞台边缘附近时,舞台会自动向该方向滚动,从而实现流畅的无限滚动体验。