如何在fabric.js中选择和拖动对象

时间:2016-02-12 09:45:06

标签: javascript canvas fabricjs

我有这个jsfiddle作为例子我在这里使用了fabric.js,当我们点击按钮时会创建行...我的问题是如何在canvas.js中选择或移动画布中的对象?

var canvas = new fabric.Canvas('c', { selection: false });

var line, isDown;

canvas.on('mouse:down', function(o){
  isDown = true;
  var pointer = canvas.getPointer(o.e);
  var points = [ pointer.x, pointer.y, pointer.x, pointer.y ];
  line = new fabric.Line(points, {
    strokeWidth: 5,
    fill: 'red',
    stroke: 'red',
    originX: 'center',
    originY: 'center'
  });
  canvas.add(line);
});

canvas.on('mouse:move', function(o){
  if (!isDown) return;
  var pointer = canvas.getPointer(o.e);
  line.set({ x2: pointer.x, y2: pointer.y });
  canvas.renderAll();
});

canvas.on('mouse:up', function(o){
  isDown = false;
});

如果我将第一行设为var canvas = new fabric.Canvas('c', { selection: true });我可以获得边界框,但我可以“无法拖动”

1 个答案:

答案 0 :(得分:1)

我解决了这个问题。

var canvas = new fabric.Canvas('c', { selection: false });

var line, isDown;

canvas.on('mouse:down', function(o){
    if(canvas.findTarget(o.e))return;
  isDown = true;
  var pointer = canvas.getPointer(o.e);
  var points = [ pointer.x, pointer.y, pointer.x, pointer.y ];
  line = new fabric.Line(points, {
    strokeWidth: 5,
    fill: 'red',
    stroke: 'red',
    originX: 'center',
    originY: 'center'
  });
  canvas.add(line);
});

canvas.on('mouse:move', function(o){
  if (!isDown) return;
  var pointer = canvas.getPointer(o.e);
  line.set({ x2: pointer.x, y2: pointer.y });
  line.setCoords();
  canvas.renderAll();
});

canvas.on('mouse:up', function(o){
  isDown = false;
});