【问题标题】:how to select and drag objects in fabric.js如何在 fabric.js 中选择和拖动对象
【发布时间】:2016-02-14 12:53:26
【问题描述】:

我以jsfiddle 为例,在这里我使用了fabric.js,当我们单击按钮时会创建线条。我的问题是如何在fabric.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 });,我可以获得边界框,但我无法拖动

【问题讨论】:

    标签: javascript canvas fabricjs


    【解决方案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;
    });
    

    【讨论】:

      猜你喜欢
      • 2013-01-28
      • 2012-01-13
      • 2013-11-25
      • 2013-11-27
      • 1970-01-01
      • 2020-11-18
      • 2017-01-29
      • 2013-12-18
      • 1970-01-01
      相关资源
      最近更新 更多