Javascript - Canvas image never appears on first function run

Posted by Matt on Stack Overflow See other posts from Stack Overflow or by Matt
Published on 2012-05-30T22:37:47Z Indexed on 2012/05/30 22:40 UTC
Read the original article Hit count: 242

Filed under:
|
|

I'm getting a bit of a weird issue, the image never shows the first time you run the game in your browser, after that you see it every time. If you close your browser and re open it and run the game again, the same issue occurs - you don't see the image the first time you run it.

Here's the issue in action, just hit a wall and there's no image the first time on the end game screen.

Any help would be appreciated.

Regards,

Matt

function showGameOver()
    {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        ctx.fillStyle = "black";
        ctx.font = "16px sans-serif";

        ctx.fillText("Game Over!", ((canvas.width / 2) - (ctx.measureText("Game Over!").width / 2)), 50);

        ctx.font = "12px sans-serif";

        ctx.fillText("Your Score Was: " + score, ((canvas.width / 2) - (ctx.measureText("Your Score Was: " + score).width / 2)), 70);

        myimage = new Image();
        myimage.src = "xcLDp.gif";

        var size = [119, 26],                       //set up size
        coord = [443, 200]; 

        ctx.font = "12px sans-serif";
        ctx.fillText("Restart", ((canvas.width / 2) - (ctx.measureText("Restart").width / 2)), 197);

        ctx.drawImage(                         //draw it on canvas
        myimage,
        coord[0],
        coord[1],
        size[0],
        size[1]
        );

        $("canvas").click(function(e) {            //when click..
            if ( testIfOver(this, e, size, coord) ) {
                startGame();                 //reload
            }
        });

        $("canvas").mousemove(function(e) {        //when mouse moving
            if ( testIfOver(this, e, size, coord) ) {
                $(this).css("cursor", "pointer");  //change the cursor
            } else {
                $(this).css("cursor", "default");  //change it back
            }
        });

        function testIfOver(ele,ev,size,coord){
            if (
                ev.pageX > coord[0] + ele.offsetLeft &&  
                ev.pageX < coord[0] + size[0] + ele.offsetLeft &&
                ev.pageY > coord[1] + ele.offsetTop &&           
                ev.pageY < coord[1] + size[1] + ele.offsetTop
            ) {
            return true;
            }
            return false;
        }
    }

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about image