ponir
ponir

Reputation: 477

Javascript - Creating an Array of Image Objects for canvas?

I was trying to create an array of image objects and load the images after the windows has loaded in canvas.

Here is my code:

var canvasObj = document.getElementById('myCanvas');
var ctx = canvasObj.getContext('2d');
var imgsrcs = ["1.png", "2.png", "3.png"];
var imgs = [];
for(var i=0; i<imgsrcs.length; i++){
    imgs[i] = new Image();
    imgs[i].onload = function () {
        ctx.drawImage(imgs[i], xb,yb);
    }
    imgs[i].src = imgsrcs[i];
}

however, I am getting this error in console:

TypeError: Argument 1 of CanvasRenderingContext2D.drawImage could not be converted to any of: HTMLImageElement, HTMLCanvasElement, HTMLVideoElement, ImageBitmap.
ctx.drawImage(imgs[i], xb,yb);

What am I doing wrong?

Thanks in advance

Upvotes: 0

Views: 731

Answers (1)

Rayon
Rayon

Reputation: 36609

By the time onload event is invoked, for-loop is iterated hence value of i is length+1, as there is no element at index length+1, undefined is passed as first argument for ctx.drawImage

Use this context in the drawImage method where this === Image-Object

var canvasObj = document.getElementById('myCanvas');
var ctx = canvasObj.getContext('2d');
var imgsrcs = ["http://i.imgur.com/gwlPu.jpg", "http://i.imgur.com/PWSOy.jpg", "http://i.imgur.com/6l6v2.png"];
var xb = 0,
  yb = 0;
var imgs = [];
for (var i = 0; i < imgsrcs.length; i++) {
  imgs[i] = new Image();
  imgs[i].onload = function() {
    console.log(imgs[i]); //Check this value
    ctx.drawImage(this, xb, yb);
    xb += 50;
    yb += 50;
  }
  imgs[i].src = imgsrcs[i];
}
<canvas id="myCanvas"></canvas>

Upvotes: 2

Related Questions