Tania339
Tania339

Reputation: 3

Multiple images in html5 canvas not stacking in the right sequence

I'm adding multiple png transparent images to an html5 canvas one above the other but they don't stack in the right sequence (defined by the array containing the url of these images)

I read in other discussions that it may be a closure problem but no solution as far.

This is my code:

function drawCanvas() {
  var canvas;
  var context;
  var imgArray = [
    'images/img1.png',
    'images/img2.png',
    'images/img3.png',
    'images/img4.png',
    'images/img5.png',
    'images/img6.png'
  ];
  canvas = document.getElementById('myCanvas');
  context = canvas.getContext("2d");
  for (var i = 0; i < imgArray.length; i++) {
    var img = new Image();
    img.src = imgArray[i];

    var drawTee = function(i, context, canvas) {
      return function() {
        console.log(i, 'loaded')
        context.drawImage(this, 0, 0);
      }
    };
    img.onload = drawTee(i, context, canvas);
  }
};

Can anyone help me?

Upvotes: 0

Views: 948

Answers (1)

devnull69
devnull69

Reputation: 16564

The problem is that the order of images on the canvas is determined by the order in which the images finish loading.

Solution: Wait for all the images to finish loading and then add them to the canvas

function drawCanvas() {
  var canvas;
  var context;
  var imgArray = [
    'images/img1.png',
    'images/img2.png',
    'images/img3.png',
    'images/img4.png',
    'images/img5.png',
    'images/img6.png'
  ];
  var images = [];
  canvas = document.getElementById('myCanvas');
  context = canvas.getContext("2d");
  var loadCount = 0;
  for (var i = 0; i < imgArray.length; i++) {
    var img = new Image();
    img.src = imgArray[i];
    images.push(img);

    img.onload = function() {
       if(++loadCount == imgArray.length) {
          for(var i=0; i < imgArray.length; i++) {
             context.drawImage(images[i], 0, 0);
          }
       }
    };
  }
};

Upvotes: 1

Related Questions