Hir*_*uri 1 javascript fabricjs
我在画布的中心创建了一条垂直线,我希望我的形状通过它的中心水平对齐,当它靠近它时就在这条线上(如果用户不想对齐,可以将其取出) )。
我的 JSFiddle 有问题:https ://jsfiddle.net/z0u05hee/5/
问题是,当形状移动时,它会停留在线中心附近,我再也无法将其取出。
这是我的 FabricJS 代码:
var canvas = new fabric.Canvas('c', { selection: false });
var line9 = new fabric.Line([
canvas.width / 2, 0,
canvas.width / 2, canvas.width
],{
stroke: 'green',
})
line9.selectable = false;
line9.evented = false;
canvas.add(line9);
canvas.add(new fabric.Circle({
left: 10,
top: 100,
radius: 50,
fill: '#9f9',
originX: 'left',
originY: 'top',
centeredRotation: true
}));
canvas.on('object:moving', function(options) {
if (Math.round(options.target.left) < (canvas.width / 2) - 15 ||
Math.round(options.target.left) > (canvas.width / 2) + 15) {
options.target.set({
left: Math.round(canvas.width / 2),
}).setCoords();
}
});
Run Code Online (Sandbox Code Playgroud)
我应该如何修复我的代码?
更新 :
canvas.on('object:moving', function(options) {
if (Math.round(options.target.left) >= (canvas.getActiveObject().getWidth()) - 20 && Math.round(options.target.left) <= (canvas.getActiveObject().getWidth()) + 20) {
options.target.set({
left: (canvas.width / 2) - canvas.getActiveObject().getWidth() / 2,
}).setCoords();
}
});
Run Code Online (Sandbox Code Playgroud)
这有效,但是当我缩放形状时,中心点会改变它的协调性。
如果我理解正确的话,应该这样做:
对您的代码(相关部分)进行小幅调整:
var snapZone = 15;
canvas.on('object:moving', function(options) {
var objectMiddle = options.target.left + options.target.getWidth() / 2;
if (objectMiddle > canvas.width / 2 - snapZone &&
objectMiddle < canvas.width / 2 + snapZone) {
options.target.set({
left: canvas.width / 2 - options.target.getWidth() / 2,
}).setCoords();
}
});
Run Code Online (Sandbox Code Playgroud)
以及所有重要的 JSFiddle 更新,https: //jsfiddle.net/rekrah/9k9hd49u/ 。
| 归档时间: |
|
| 查看次数: |
1476 次 |
| 最近记录: |