Dexter
Dexter

Reputation: 33

Is it possible to use multiple images in an HTML5 canvas?

I'm trying to load 10 different images into a canvas. My plan is to eventually animate these images but right now they seem to be overwriting one another. Here is my code:

var DrawLetters = function()
{
    for (i = 0; i < howManyLetters; i++)
    {
        thisWidth = letters[i][0];
        thisHeight = letters[i][1];
        imgSrc = letters[i][2];
        letterImg = new Image();
        letterImg.onload = function()
        {
            context.drawImage(letterImg,thisWidth,thisHeight);
        }
        letterImg.src = imgSrc;
    }
};

letters is an array with 10 elements where each element contains a path to the image. Any help on this would be greatly appreciated.

Upvotes: 3

Views: 6763

Answers (3)

helios
helios

Reputation: 13841

I've tried your code and the onload method always use the LAST value of the vars, not the value when the array was iterated.

Try setting the X and the Y to properties of the image object:

// I assume you are storing the coordinates where the letters must be
letterImg.setAtX = letter[i][XPOS];
letterImg.setAtY = letter[i][YPOS];

and on the onload:

context.drawImage(this, this.setAtX, this.setAtY);

this is the image raising the onload event.

Edit I've changed the properties used to carry the coordinates. Now they're setAtX/Y. You cannot use x and y because they're reserved.

Upvotes: 4

Zirak
Zirak

Reputation: 39848

You're drawing them on the same point. drawImage doesn't care about the height or width with your given parameters; it just wants an image and a coordinate. See https://developer.mozilla.org/en/Canvas_tutorial/Using_images

So, you're gonna need to give your images more data; something like:

    thisWidth = letters[i][0];
    thisHeight = letters[i][1];
    imgSrc = letters[i][2];
    thisX = letters[i][3]; //<---
    thisY = letters[i][4]; //<---
    letterImg = new Image();
    letterImg.onload = function()
    {
        context.drawImage(letterImg, thisX, thisY, thisWidth, thisHeight);
        //or, just
        context.drawImage(letterImg, thisX, thisY);
    }
    letterImg.src = imgSrc;

Edit: Just had a thought - you can do it dymagically:

context.drawImage(letterImg, letters[i-1][0]+thisWidth, letters[i-1]+thisHeight, thisWidth, thisHeight);

With this way you'll have to check for stuff, but I think you get the overall intention.

Upvotes: 1

Felipe
Felipe

Reputation: 1310

You have to reposition the draw start position every time so the images arent overwritten.

[context . drawImage(image, dx, dy, dw, dh)][1]

There's an image on the link explaning what every parameter means.

Upvotes: 0

Related Questions