2017-09-13 42 views
0

我希望可选对象在点击时将其中心捕捉到我的鼠标光标。在这种情况下,对用户的唯一修改是移动对象,不进行缩放,旋转等。只需更新mousedownselected上对象的位置,将只更新其位置,直到moving事件被触发,对象将在其中到原来的位置,然后开始跟随鼠标。FabricJS - 更好的解决方案,选中时在光标上居中对象?

rect.on('moving', moveHandler); 
function moveHandler(evt) { 
var mousePnt = $canvas.getPointer(evt.e); 
rect.set({ 
    left:mousePnt.x - rect.width*0.5 , top:mousePnt.y - rect.height*0.5}); 
this.setCoords(); 
} 

这是我想出居中光标可选择的长方形,但我敢肯定它发射了两枚运动事件。有没有办法来覆盖原来的定位。或者我应该自己编写mousedown,mouseupmoving侦听器来模仿默认的拖动行为?

回答

0

如果不涉及旋转或缩放,则您的解决方案很好。

如果不是.setCoords,在移动过程中是可选的,因为它将在翻译完成时在mouseUp上调用时,您不会执行任何超出必要的任何操作。

如果你想利用鼠标按下的办法,改变位置一劳永逸,你可以用这样的逻辑:

var canvas = new fabric.Canvas('c'); 
 
canvas.add(new fabric.Rect({width: 50, height: 50})); 
 
canvas.on('mouse:down', function(opt) { 
 
    if (this._currentTransform && opt.target) { 
 
    var target = opt.target; 
 
    target.top = this._currentTransform.ey - target.height/2; 
 
    target.left = this._currentTransform.ex - target.width/2; 
 
    this._currentTransform.left = target.left; 
 
    this._currentTransform.offsetX = this._currentTransform.ex - target.left; 
 
    this._currentTransform.offsetY = this._currentTransform.ey - target.top; 
 
    this._currentTransform.top = target.top; 
 
    this._currentTransform.original.left = target.left; 
 
    this._currentTransform.original.top = target.top; 
 
    this.renderAll(); 
 
    } 
 
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.18/fabric.min.js"></script> 
 
<canvas id="c" ></canvas>

您必须修改所有的面料注意变换信息在你的mousedown处理程序执行之前,先关闭mouseDown事件。

相关问题