FabricJs多个画布多次加载相同的图像

时间:2018-03-15 11:38:34

标签: javascript fabricjs

我有一个1-2循环,在循环内我在屏幕上创建了两个画布并将它们存储在一个对象中,然后在每个画布上加载相同的两个图像,但图像仅出现在最后一个画布上。为什么不在两幅画布上加载?还有一个文本对象可以在同一个循环中的两个画布上工作。

示例代码,它实际上只是将图像添加到屏幕上的第二个画布并忽略第一个,但文本对象被添加到两个?

var canvases = {};
var imageUrls = ['url here','url 2 here'];
for(var p = 1; p <= 2; p++){
    canvases[p] = new fabric.Canvas('canvas-element-'+p);
    var t = new fabric.Text('Testing',{top:600,left:0});
    canvases[p].add(t);
    canvases[p].renderAll();
    for(var i in imageUrls){
        fabric.Image.fromUrl(imageUrls[i],function(img){
            img.set({
                width:500,
                height:500,
                top:0,
                left:0
            });
            canvases[p].add(img);
            canvases[p].renderAll();
        }
    });
}

1 个答案:

答案 0 :(得分:2)

  1. imageUrls数组包含您在1和2处访问的0和1位置的图像。
  2. fabric.Image.fromUrl函数名称为fabric.Image.fromURL

  3. 由于加载图像是异步函数,您需要保留自调用函数或只需使用let for for循环for (let p = 1; p <= 2; p++) {

  4. &#13;
    &#13;
    var canvases = {};
    var imageUrls = ['', 'https://via.placeholder.com/300x300?text=canvas1', 'https://via.placeholder.com/300x300?text=canvas2'];
    for (var p = 1; p <= 2; p++) {
      canvases[p] = new fabric.Canvas('canvas-element-' + p);
      var t = new fabric.Text('Testing', {
        top: 600,
        left: 0
      });
      canvases[p].add(t);
      canvases[p].renderAll();
      (function(index) {
        fabric.Image.fromURL(imageUrls[p], function(img) {
          img.set({
            width: 500,
            height: 500,
            top: 0,
            left: 0
          });
          canvases[index].add(img);
          canvases[index].renderAll();
        });
      })(p);
    }
    &#13;
    canvas{
     border :2px solid #000
    }
    &#13;
    <script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
    <canvas id='canvas-element-1' width=300 height=300></canvas>
    <canvas id='canvas-element-2' width=300 height=300></canvas>
    &#13;
    &#13;
    &#13;