1

I am using fabric.js to render images on canvas. Trying to render 3 images with different properties (like localization, source, etc.).

for (i = 0; i < 3; i++) {
  // read data from XML
  // ... read: imageWidth, imageHeight, etc.

  var imageDefaults = {
    width: imageWidth,
    height: imageHeight,
    left: imageX,
    top: canvas.height - imageY,
    angle: imageRotation
  };

  console.log('outside callback fun');

  fabric.Image.fromURL(imagePath, function (image) {
    image.set(imageDefaults).setCoords();                                    
    canvas.add(image);
    console.log('inside callback fun');                 
  });
}

The output console log is:

outside callback fun
outside callback fun
outside callback fun
inside callback fun
inside callback fun
inside callback fun

As a result, I receive 3 images with the same properties (for i == 2).

How to ensure loop continuation only if image is rendered? I tried to set while loop after rendering image, but this loop is running infinitely.

Maciej Aniol
  • 33
  • 1
  • 4

2 Answers2

2

Add a wrapper function inside your for loop.

for (i = 0; i < 3; i++) {
     (function(i){
      // read data from XML
      // ... read: imageWidth, imageHeight, etc.

      var imageDefaults = {
        width: imageWidth,
        height: imageHeight,
        left: imageX,
        top: canvas.height - imageY,
        angle: imageRotation
      };

      console.log('outside callback fun');

      fabric.Image.fromURL(imagePath, function (image) {
        image.set(imageDefaults).setCoords();                                    
        canvas.add(image);
        console.log('inside callback fun');                 
      });
     })(i);
    }
Zee
  • 8,420
  • 5
  • 36
  • 58
1

Try recursive solution:

function SetImageUrl(index, maxIndex, callback){
    ...

    var imageDefaults = {
      width: imageWidth,
      height: imageHeight,
      left: imageX,
      top: canvas.height - imageY,
      angle: imageRotation
    };

    console.log('outside callback fun');

    fabric.Image.fromURL(imagePath, function (image) {
      image.set(imageDefaults).setCoords();                                    
      canvas.add(image);
      console.log('inside callback fun');
      if(index < maxIndex){
           callback(index++, maxIndex, callback);
      }

  });
}

Usage:

SetImageUrl(0, 3, SetImageUrl);
freethinker
  • 2,257
  • 4
  • 26
  • 49