Skip to main content

HTML5 Canvas 拖拽一条线

要使用 Konva 拖拽一条线,我们可以在实例化线条时将配置对象的 draggable 属性设置为 true,或者可以使用 draggable() 方法。

注意:(!) 拖拽一条线不会更改 points 属性。相反,线条的 x 和 y 属性会发生更改。

import Konva from 'konva';

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

const layer = new Konva.Layer();

const redLine = new Konva.Line({
x: 50,
y: 50,
points: [0, 0, 150, 0],
stroke: 'red',
strokeWidth: 15,
lineCap: 'round',
lineJoin: 'round',
draggable: true,
});

// 添加鼠标样式
redLine.on('mouseover', function () {
document.body.style.cursor = 'pointer';
});
redLine.on('mouseout', function () {
document.body.style.cursor = 'default';
});

layer.add(redLine);
stage.add(layer);