Fabric.js 图像点击和外部动画添加功能

Fabric.js image on click and animate outside add function

您好,我正在开发一个带有 Fabric.js 的应用程序,用户可以在其中输入一些字符串,点击删除图片后,最后一个词将被删除,图片将向左移动。

我正在使用像

这样的图片
fabric.Image.fromURL(srcImg, function (oImg) {
    canvas.add(oImg);
    oImg.set('left',0);
    oImg.set('top', 100);
    oImg.scale(.55);
    canvas.renderAll();

    // and then, we can animate the image    
    oImg.animate('left', 100, {
        onChange: canvas.renderAll.bind(canvas)
    });
    
    oImg.on('mouse:down', function() {
        //some function here
    });
 });

现在我想在添加功能之外使用点击和动画,但出现错误undefined index oImg。我想在其他地方使用点击和动画,这样我就可以删除最后一个词并使用动画将图像向左移动我现在使用文本进行点击和动画,但我想使用图像。

fabric.Image.fromURL是一个异步方法,所以在它下面直接调用它会抛出undefined的错误是正常的。你这里主要有两个解决方案:

  1. 在回调中添加事件监听器:

    fabric.Image.fromURL('//lorempixel.com/200/200/', function(img) {  
      img2 = img
    
      ...
    
      img2.on('mousedown', function () {
        console.log('throws an error');
      });
    });
    
  2. 调用事件绑定函数(总是在创建 img2 之后)

    fabric.Image.fromURL('//lorempixel.com/200/200/', function(img) {  
      img2 = img
    
      ...
    
      bindImageEvents(img2)
    });
    
     function bindImageEvents (imageObject) {
       imageObject.on('mousedown', function () {
         console.log('Something...');
     });
    }