Reputation: 143
I am currently have a problem with loading images and draw in canvas. In localhost , it work smoothly but when put to my web server it not work as smooth as localhost at all. I need to refresh page two to tree time then it work. So is there alternative ways to deal with this. The following is my sample code
function action1() {
var imgObj = new Image()
timer = setInterval(function(){
imgObj.src = 'img/velOpen/' + (index++) + '.png';
imgObj.onload = function(){
context.clearRect(0,0, context.canvas.width, context.canvas.height);
context.drawImage(imgObj, X, y);
}
},100);
};
Note: I have serval images with size of only 32 kb
Upvotes: 0
Views: 636
Reputation: 31813
You need to wait until all images are loaded before you start drawing to the canvas.
Here's an example of how to call a function immediately after the last image loads.
function loadImageGroup(urls, onCompleteFunc) {
var numImagesNotYetLoaded = urls.length;
var urlToImageMap = {};
var markLoaded = function() {
if (--numImagesNotYetLoaded == 0)
onCompleteFunc(urlToImageMap);
}
for (var i = 0; i < urls.length; i++) {
var img = new Image();
img.onload = markLoaded;
img.src = urls[i];
urlToImageMap[urls[i]] = img;
}
}
var urls = [
'http://www.google.com/images/srpr/logo3w.png'
, 'http://www.google.com/images/icons/product/chrome-48.png'
];
loadImageGroup(urls, function(urlToImageMap) {
//all are loaded. draw to canvas here
var imgObject = urlToImageMap['http://www.google.com/images/srpr/logo3w.png'];
alert(imgObject.width)
});
That's just a sample. I say that because it's not totally robust. Imagine if an image failed to load for some reason - the on complete function would never be called. Maybe you would want a timeout or something...
Upvotes: 1