I was experimenting with the Canvas tag, and the code below worked great on Firefox, but would not on Safari or Chrome:


function draw(img) {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
	var image = new Image();
	image.src = "http://localhost:3000" + img;
	var context = canvas.getContext("2d");
	context.drawImage(image,0,0);
    }
}

Quite baffling. No errors on the javascript console either. It took me a little while to figure out that the problem.

The problem is that the browser may load images simultaneously while executing your javascript If the image load is not complete, well, your image does not display properly, and as far as the browser is concerned, there is no problem. (interesting how firefox 4 beta worked every time)

The solution? Attach an event listener,


window.addEventListener("load",draw,true);

function draw(img) {
     var canvas = document.getElementById("canvas");
if (canvas.getContext) {
	var image = new Image();
	image.src = "http://localhost:3000" + img;
	var context = canvas.getContext("2d");
 image.onload = function () {
		context.drawImage(image,0,0);
	}

Notice the addition of the eventlistener and the onload. That fixed it.

 

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>