Drawing an image to the canvas onClick wont work on first click

  You are currently not logged in. You can view the forums, but cannot post messages. Log In | Register

29-Feb-12 15:33
I want to draw an image to the canvas on user click. My code works but only after the user clicks the button a second time after the page is first loaded. If you click twice then reload the page it will draw the image on the first click. If you then close all you browser windows then open the page again then you have to click twice again. I'm not sure what’s causing this behavior. I’ve tried it in Firefox, Chrome and IE all exhibit the same behavior. Below is the code:


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function draw_Domino(){
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img2=new Image();

img2.src='two_six.png';
ctx.drawImage(img2,0,0);
}
</script>
</head>

<body>
<canvas id="myCanvas" width="600" height="600" style="border-style:solid;border-color:#B9D0D0;border-width:3px;">
your browser does not support the canvas tag </canvas>

<button onClick="draw_Domino()" style="height:50px;width:50px;background-color:green">Go</button>
</body>
</html>
05-Mar-12 00:00
@ragn0r: Probably because your image hasn't fully loaded into the browser at the point you call drawImage(). Either preload your image, or add a "load" event handler to the image and call drawImage() inside the handler.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/

 
New posts
Old posts

Follow Elated