Question

I'm trying to draw images from an array in such a loop:

var frames = [];
for(var i=0;i<assets.length;i++){
    frames[i] = new Image();
    frames[i].onload = function() {
        ctx.drawImage(frames[i],10,10);         
    };
frames[i].src = assets[i];

and get the error:

Value could not be converted to any of: HTMLImageElement, HTMLCanvasElement, HTMLVideoElement.

I seems like the way "frames[i]" is passed to drawImage() is causing the problem. Why is that so and what is the proper way to do it? Is the variable "i" not valid in the context that the onload function is called?

Thanks

Was it helpful?

Solution

Your problem is that the onload callback is asynchronous, so when the callback function is called, the loop may have ended, and the i variable isn't defined anymore. Anyway, the this keyword point to the image inside the callback :

var frames = [];
for (var i=0; i<assets.length; i++) {
    frames[i] = new Image();
    frames[i].onload = function() {
        ctx.drawImage(this, 10, 10);         
    };
    frames[i].src = assets[i];
}

The next problem you'll may have is that you won't control in which order the images are drawn on the canvas. See this JsFiddle.

OTHER TIPS

I'd try the following code:

var frames = [];
for (var i=0; i<assets.length; i++)
{
    frames[i] = new Image();
    frames[i].addEventListener(load, onImageLoaded, false);
    frames[i].src = assets[i];
}
function onImageLoaded(e)
{
    ctx.drawImage(this, 10, 10);
}

The rationale being that you dont need to maintain the variable i, also that it makes the code cleaner to read. Since the onImageLoaded handler function is attached in this manner, each time it's called, the this variable will hold what would have equated to frames[i], where i holds the appropriate value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top