Reputation: 36289
I have discovered some race conditions with drawing an HTML5 canvas
programmatically in JavaScript
. These occur when trying to modify an image before it is loaded, and I have been able to fix most of them using the technique:
var myImage = document.createElement('img');
myImage.onload = function(){
console.log("image src set!");
};
myImage.src="img/foobar.png";
I am doing this operation for one of several images, and am having a strange thing happen. Basically, the image is drawing to the canvas before it is loaded. I even tried to hack-around the issue by using a boolean value to specify if the image has been drawn yet. Here is my code with the output. To understand the context, this code is part of a function that is called every second to update the canvas.
if (!at_arrow_black)//one of two images used to show an arrow on the canvas
{
at_arrow_black = document.createElement('img');
at_arrow_black.onload = function() {
if (foregroundColor === "black")//which image to draw depends on the foreground color
{
console.log("black load");
context.drawImage(at_arrow_black, canvas.width*.775, canvas.height*.66, canvas.width*.075, font*4/5);
}
};
at_arrow_black.src = "img/at_arrow.png";
}
else
{
if (foregroundColor === "black")
{
if (hasDrawnArrow)//this starts as false
{
console.log("1. black draw");
context.drawImage(at_arrow_black, canvas.width*.775, canvas.height*.66, canvas.width*.075, font*4/5);
}
else
{
logDebug("2. black draw");
hasDrawnArrow = true;
}
}
}
This results in the canvas first drawing one arrow, then the other, at the first iteration of this loop (and in slightly different places). The output I get:
2. black draw
black load
1. black draw
This is the expected output - but why does the canvas draw the image anyways? Is this a race condition of some sort? What can I do to fix it?
Upvotes: 1
Views: 1031
Reputation: 9465
I know there is already an accepted answer, but here is an alternative anyway.
You need to wait until all your images are loaded. I use an image loader that sets a flag when all images are loaded so my script can then continue.
function ImageLoader(sources, callback)
{
var images = {};
var loadedImages = 0;
var numImages = 0;
// get num of sources
for (var src in sources) {
numImages++;
}
for (var src in sources) {
images[src] = new Image();
images[src].onload = function() {
if (++loadedImages >= numImages) {
callback(images);
}
};
images[src].src = sources[src];
}
}
// *** The images you want to laod
var sources = {
background: 'images/bg.png',
assets: 'images/assets.png',
};
// *** What you want to happen once all images have loaded...
ImageLoader(sources, function(images) {
// *** Example of what I usually do
_images = images;
_setImagesReady = true;
});
// *** Access the image by specifying it's property name you defined. eg:
ctx.drawImage(_image.background, 0, 0);
Upvotes: 0
Reputation: 105015
If you're loading more than 1 image, you will probably want to build yourself an image loader so all images are loaded before you start working with them.
Here is an example:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas1=document.getElementById("canvas1");
var ctx1=canvas1.getContext("2d");
var canvas2=document.getElementById("canvas2");
var ctx2=canvas2.getContext("2d");
var imageURLs=[];
var imagesOK=0;
var imagesFailed=0;
var imgs=[];
imageURLs.push("http://upload.wikimedia.org/wikipedia/commons/d/d4/New_York_City_at_night_HDR_edit1.jpg");
imageURLs.push("http://www.freebestwallpapers.info/bulkupload//20082010//Places/future-city.jpg");
loadAllImages();
function loadAllImages(){
for (var i = 0; i < imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = onLoad;
img.onerror = onFail;
img.src = imageURLs[i];
}
}
var imagesAllLoaded = function() {
if (imagesOK+imagesFailed==imageURLs.length ) {
// all images are processed
// ready to use loaded images
// ready to handle failed image loads
ctx1.drawImage(imgs[0],0,0,canvas1.width,canvas1.height);
ctx2.drawImage(imgs[1],0,0,canvas2.width,canvas2.height);
}
};
function onLoad() {
imagesOK++;
imagesAllLoaded();
}
function onFail() {
// possibly log which images failed to load
imagesFailed++;
imagesAllLoaded();
};
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas1" width=300 height=300></canvas><br/>
<canvas id="canvas2" width=300 height=300></canvas>
</body>
</html>
Here's the JSFiddle.
Upvotes: 1