我想扩展fabric.Line类以确保它始终是水平或垂直的(取决于施工期间的选项)
我通过重写 setCoords 来确保这一点,
setCoords() {
if (this.orientation === 'horizontal') {
this.set({ y2: this.y1 });
} else {
this.set({ x2: this.x1 });
}
super.setCoords()
}
绘制线条时效果很好,但拖动线条时则不起作用。释放时,线会“跳回”到原来的位置。
为什么它会跳回来,有没有更好的方法来确保我的线始终保持水平/垂直?
您的方法 setCoords() 有效,但拖动鼠标时需要重新绘制线条。
在此示例中,我创建了一个基于一组坐标绘制线条的函数。然后鼠标事件侦听器使用更新后的坐标调用该函数。
您需要根据需要修改方向变量。
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"></script>
</head>
<body>
<canvas id="canvas" width="500" height="300" style="border:1px solid #000000"></canvas>
<script>
var canvas = new fabric.Canvas("canvas");
canvas.selection = false;
var hvline = null;
var coords = [];
var dragging = false;
var HVLine = fabric.util.createClass(fabric.Line, {
type: 'hvline',
initialize: function(points, options) {
options = options || {};
this.points = points || [];
this.callSuper('initialize',points, options);
this.set('orientation', options.orientation || 'horizontal');
},
setCoords: function(ctx) {
if (this.orientation === 'horizontal') {
this.set({ y2: this.y1 });
} else {
this.set({ x2: this.x1 });
}
this.callSuper('setCoords', ctx);
},
});
function drawLine(coords) {
if (hvline != null) {
canvas.remove(hvline);
}
hvline = new HVLine(
coords,
{
stroke: "blue",
strokeWidth: 4,
hasControls: false,
hasBorders: false,
selectable: false,
lockMovementX: true,
lockMovementY: true,
hoverCursor: "default",
originX: "center",
originY: "center",
orientation: 'vertical'
}
);
canvas.add(hvline);
}
canvas.on('mouse:up', function (e) {
dragging = false;
hvline = null;
});
canvas.on('mouse:move', function (e) {
var pointer = canvas.getPointer(event.e);
var positionX = pointer.x;
var positionY = pointer.y;
if (dragging) {
coords[2] = positionX;
coords[3] = positionY;
drawLine(coords);
}
});
canvas.on("mouse:down", function(event) {
var pointer = canvas.getPointer(event.e);
var positionX = pointer.x;
var positionY = pointer.y;
dragging = true;
coords = [positionX, positionY, positionX, positionY];
drawLine(coords);
});
canvas.renderAll();
</script>
</body>
</html>