简体   繁体   中英

FabricJS - Better solution to centering object on cursor when selected?

I would like selectable objects to snap their center to my mouse cursor on click. The only modification allowed to the user in this case is moving the object, no scaling, rotating, etc. Simply updating the position of the object on mousedown or selected will update its position only until the moving event is fired, where the object will snap to its original position and then begin following the mouse.

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();
}

This is what I've come up with to center a selectable rectangle on the cursor, but I'm certain it's firing two movement events. Is there a way to override that original positioning. Or should I instead write my own mousedown , mouseup , and moving listeners to mimic the default dragging behavior?

You solution is fine if no rotating or scaling is involved.

You are not executing anything more than necessary if not the .setCoords that during a movement is optional since it will be called on mouseUp when the translation is finished.

If you want to take the mouseDown approach, changing the position once for all, you can use this logic:

 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> 

You have to modify all the transform information that fabric noted down on the mouseDown event before the your mousedown handler is executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM