I am developing an HTML and js app that will run on IOS devices. In this app I am using lots of images and using src to set the path of these images inside a function. After this function pletes i am calling another function where I am drawing a canvas, the problem is that all these images are not loading properly, some of the images's width remains 0. How can I ensure that all the images are getting loaded properly before i call the next function.
Thanks
I am developing an HTML and js app that will run on IOS devices. In this app I am using lots of images and using src to set the path of these images inside a function. After this function pletes i am calling another function where I am drawing a canvas, the problem is that all these images are not loading properly, some of the images's width remains 0. How can I ensure that all the images are getting loaded properly before i call the next function.
Thanks
Share Improve this question edited Mar 27, 2012 at 15:27 Simon Sarris 63.9k13 gold badges149 silver badges174 bronze badges asked Mar 27, 2012 at 15:22 user1000397user1000397 331 gold badge3 silver badges9 bronze badges 2- 6 We need to see your relevant code. – Michael Berkowski Commented Mar 27, 2012 at 15:23
- 1 possible duplicate of HTML5 canvas drawImage not working on first click – Simon Sarris Commented Mar 27, 2012 at 15:27
3 Answers
Reset to default 4Please do more searching before you ask a question.
Waiting for the images to finish loading is easy:
var img = new Image(); // Create new img element
img.onload = function(){
// execute drawImage statements here
};
img.src = 'myImage.png'; // Set source path
Make sure the onload event has fired for each image before trying to draw. If you have multiple images and don't want to make something plicated then there are libraries that do this for you, such as pxloader.
This will ensure all your images are loaded
var images = [{src: "foo.jpg"},{...}];
var loaded = 0;
function loadImages(){
for(var i=0;i<images.length;++i){
var tmp = new Image;
tmp.onload = function(){loaded++;if(loaded == images.length){nextStep();}};
tmp.src = images[i].src;
}
function nextStep(){
console.log("everything loaded");
}
loadImages();
you can use the image onload event to trigger code to run when the image is fully loaded; below is an example. The code in the handler attached to image.onload runs when the image is fully loaded somewhere after I set the image.src.
var p = {
display: function(imageUrl) {
var availableDimensions = this.getAvailableDimensions();
$("#loadingImg").css("display", "none");
var canvas = document.getElementById("myCanvas");
var image = new Image();
image.onload = function() {
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext("2d").drawImage(image, 0, 0, image.width, image.height);
canvas.style.display = "inline";
};
image.src = imageUrl + "&width=" + availableDimensions.width + "&height=" + availableDimensions.height + "&negative=false";
}
}