Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html5 drawImage works in firefox, not chrome

I've just recently started dabbling in HTML5/Javascript, and am currently trying to put together a simple blackjack game. My main browser is Chrome, and I'd noticed my draw function for cards wasn't working. I simplified the code quite a bit, but the drawImage() function still didn't seem to put anything on the screen.

$(document).ready(function(){
 init();
});

function init(){
 setCanvas();
}

function setCanvas(){
 var canvas = document.getElementById("game-canvas");
 var context = canvas.getContext("2d");
 canvas.width = 800
 canvas.height = 600
 context.fillStyle = "#004F10";
 context.fillRect(0,0,800,600);
 var back = new Image();
 back.src = "testermed.png"
 context.drawImage(back,54,83);

}

Now when I run this in Chrome, I get the box drawn by the context but NOT the image drawn. However when I run it in Firefox the image and box show up just fine. From what I can tell Firefox and Chrome both support HTML5 canvas equally; any ideas as to why it won't work on Chrome?

like image 574
Curlystraw Avatar asked Sep 12 '12 11:09

Curlystraw


People also ask

Which is the method used to draw image on a canvas?

The drawImage() method draws an image, canvas, or video onto the canvas. The drawImage() method can also draw parts of an image, and/or increase/reduce the image size. Note: You cannot call the drawImage() method before the image has loaded.


1 Answers

Try to write instead of context.drawImage(...) this:

back.onload = function() {
    context.drawImage(back, 54, 83);
}
like image 76
micnic Avatar answered Oct 05 '22 12:10

micnic