jeudi 16 avril 2015

Drawing multiple images on an HTML5 canvas doesn't work sometimes

I'm trying to draw multiple images inside a canvas. When I load a page it works (every image draws in the correct location), the issue I'm having is that when I reload the page only 1 image will draw (in it's correct location).


The code is simply a for loop that goes through an array of image URLs and determines where that image is supposed to be located.


When I reload the page and only 1 image is drawn, that one image happens to be whatever image is located in the header of the page. If I go to another page that runs this same code but has a different header image it will display all the images correctly, but when I reload the page only the image that also happens to be in the header displays correctly. If I go back to the first page all the images will display correctly, and if I reload only the image that also happens to be in the header will display.



// Get the image
var image = new Image();
var image_load = function( img, x_pos, y_pos, width, height ) {

// Draw the image
context.drawImage( img, x_pos, y_pos, width, height );
};
image.src = image_url[index];
image.onload = image_load( image, x_position, y_position, img_size, img_size );


I've made sure that the image urls are all properly set and that the positions & sizes are all correct. The other thing I've noticed is that when I break through the code the image object always has the outerHTML and src attributes set correctly, but the currentSrc is only set when the image displays correctly, and is set to "" whenever it doesn't.


I've been playing with this for hours and no online example I've found has worked for me. Any help would be much appreciated.


Aucun commentaire:

Enregistrer un commentaire