Skip to main content

HTML5 Canvas 形状调整大小吸附

在某些应用程序中,您可能希望将调整大小操作吸附到某些特定值附近。吸附功能使形状在指定值附近具有“粘性”,效果类似于取整。 您可以使用 anchorDragBoundFunc 方法控制锚点位置的行为。

transformer.anchorDragBoundFunc(function (oldAbsPos, newAbsPos, event) {
// 限制 x 轴上的任何其他位置
return {
x: 0,
y: newAbsolutePosition.y,
};
});

说明:尝试调整形状的大小。您将看到变换器如何尝试吸附到参考线。

import Konva from 'konva';

const width = window.innerWidth;
const height = window.innerHeight;

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

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

// 创建参考线
const horizontalLine = new Konva.Line({
points: [0, height / 2, width, height / 2],
stroke: '#000',
strokeWidth: 1,
dash: [4, 4],
});
layer.add(horizontalLine);

const verticalLine = new Konva.Line({
points: [width / 2, 0, width / 2, height],
stroke: '#000',
strokeWidth: 1,
dash: [4, 4],
});
layer.add(verticalLine);

const rect = new Konva.Rect({
x: 60,
y: 60,
width: 100,
height: 100,
fill: 'red',
draggable: true,
});
layer.add(rect);

const tr = new Konva.Transformer({
nodes: [rect],
anchorDragBoundFunc: function (oldPos, newPos) {
const dist = Math.sqrt(Math.pow(newPos.x - width / 2, 2));
if (dist < 10) {
return {
...newPos,
x: width / 2,
};
}
return newPos;
},
});
layer.add(tr);