为什么第二个选择在Fabric.js

时间:2018-05-07 12:33:37

标签: canvas fabricjs

当我第一次点击图像时 - 它会向左移动

var canvas = new fabric.Canvas('canvas');
  canvas.on({
    'object:selected': function(e) {
      e.target.animate('left', 50, {                    
        onChange: canvas.renderAll.bind(canvas),
        duration: 100
      });
    }
  });

fabric.Image.fromURL('imag/pziiif.gif', function(img) {
  img.set({
    left:0,
    top: 0
  });
  canvas.add(img);
});

但我需要我的图像重复其动作,当我第二次点击它时。 我不明白为什么它没有发生。也许是因为选择仍在我的形象上。我应该以某种方式删除选择? 如果是这样呢?

1 个答案:

答案 0 :(得分:1)

您需要使用discardActiveObject()取消选择对象,并在每次点击使用时添加值+=50

<强> 样本

&#13;
&#13;
var canvas = new fabric.Canvas('canvas');
canvas.on('object:selected', function(e) {
  e.target.animate('left', '+=50', {
    onChange: canvas.requestRenderAll.bind(canvas),
    duration: 500,
    onComplete:function(){
     e.target.set('active',false)
     e.target.setCoords();
     canvas.discardActiveObject().requestRenderAll();
    }
  });
});

fabric.Image.fromURL('http://fabricjs.com/assets/pug.jpg', function(img) {
  img.set({
    left: 0,
    top: 0,
    scaleX: 0.3,
    scaleY: 0.3
  });
  canvas.add(img);
});
&#13;
canvas{
 border:2px solid #000;
}
&#13;
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id='canvas' width=500 height=400>
&#13;
&#13;
&#13;