Fabric.js-在不按住鼠标键的情况下移动对象 [英] Fabric.js - Move object without holding mouse button

查看:301
本文介绍了Fabric.js-在不按住鼠标键的情况下移动对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Fabric.js中,可以通过左键单击,按住并移动鼠标来在画布中移动对象.在这种情况下,所选对象跟随鼠标光标,并且触发object:moving.释放鼠标左键退出此模式.

In Fabric.js an object can be moved in the canvas by left-clicking, holding and moving the mouse. In this condition, the selected object follows the mouse's cursor and object:moving gets fired. Releasing the left mouse button exits this mode.

是否可以更改此行为,并让对象通过不同事件进入此模式?例如,单击一次使对象跟随光标(并正确触发object:moving),然后再次单击以将对象释放到最终位置?

Is there a way to change this behavior and have an object enter this mode with different events? For example, click once to have the object follow the cursor (and have the object:moving fire correctly) and then click a second time to release the object in it's final position?

考虑到已经实现了该功能,我希望避免从头开始编写此代码,而只需要更改进入/存在此模式的触发器即可.

I'm hoping to avoid writing this from scratch listening to the "mouse move" event, given that this is already implemented, but just the triggers to enter/exist this mode have to be changed.

推荐答案

我通过使用名为movedObject的变量来实现此目的,如果没有对象被移动,则该变量为null;如果对象已移动.如果在移动对象时单击,则会将movedObject设置为null.如果单击时不移动对象,则将movedObject设置为对象,如果单击了该对象.

I implemented this by having a variable called movedObject which is null if no object is moved and contains an object if an object is moved. If you click while an object is being moved then it'll set movedObject to null. If you click while not moving an object then it'll set movedObject to an object if you clicked one.

我向mouse:move添加了一个侦听器,该侦听器将movedObjectlefttop设置为鼠标xy(减去movedObject widthheight/2)如果 movedObject不是null.

I added a listener to mouse:move which sets left and top of movedObject to the mouse x and y (minus movedObject width and height / 2) if movedObject is not null.

JSFiddle

代码:

var canvas = new fabric.Canvas('canvas');
canvas.setWidth(300);
canvas.setHeight(300);
var circle = new fabric.Circle({
  radius: 30,
  fill: '#f55',
  top: 100,
  left: 100
});
canvas.add(circle);
circle.hasControls = circle.hasBorders = circle.selectable = false;

var movedObject = null;
canvas.on({
  'mouse:down': function(e) {
    //If an object is selected already it'll be unselected
    if (movedObject !== null) {
        movedObject = null;
    } else {
      //If no object was selected and a click occured on an object it'll now be selected
      if (e.target) {
         movedObject = e.target;
      }
    }
  },
  'mouse:move': function(e) {
    //Moving the object along with mouse cursor
    if (movedObject !== null) {
        movedObject.left = (e.e.clientX - movedObject.width / 2);
        movedObject.top = (e.e.clientY - movedObject.height / 2);
        movedObject.setCoords();
        canvas.renderAll();
    }
  }
});

这篇关于Fabric.js-在不按住鼠标键的情况下移动对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆