0

Possible Duplicate:
canvas drawImage doesn't draw images the first time

I have made an web application in which I have made a game, the game doesn't work on first load, it only runs when you refresh the page, on mozilla or chrome it starts again (i.e is normal). the code is as follow:

 <!DOCTYPE html>

 <html>
 <head>

<script>

function init() {

img=new Image();
img.src= "Device-Android.png";
img1= new Image();
img1.src= "background.png";
play=new Image();
play.src="play.png"; 

    canvas1 = document.getElementById('canvas');
//alert("show");        
    if (canvas1 && canvas1.getContext) {
        ctx = canvas1.getContext('2d');

ctx.drawImage(img,0,0,394,726);
ctx.drawImage(img1,37,92,317,477);
ctx.drawImage(play,149,300,70,40);
//alert("show somthing");
ctx.font = "bold 15pt sans-serif";
document.onmousedown = initGame;
    }



}
................ remaining functions

 </script>


</head>

<body onload="init();">

  <center>

   <canvas id="canvas" width="387" height="700">  <h1>Memory Game</h1>   </canvas>

    </center>
    </body>
    </html>
Community
  • 1
  • 1
shark
  • 53
  • 1
  • 8
  • @PeeHaa I have to refresh the page first time when I run it on mozilla or firefox but I want it to run automsticslly – shark Oct 05 '12 at 18:54
  • Possibly the same problem as: http://stackoverflow.com/questions/3850312/canvas-drawimage-doesnt-draw-images-the-first-time?rq=1 – VoidMain Oct 05 '12 at 18:57

1 Answers1

0

It may be that your images are not completely loaded when you try to draw them. When you onload=init(){image.src="...";} it is the image.src call that starts loading the image. If you are immediately drawing to canvas (a few lines later) it isn't done loading yet. When you reload the page then it is in the cache from last page load.

Write a pre-loader. Or load those images before calling init().

There is a variable to tell you if an image is done loading. I think it is image.complete