0

I'm trying to get a background image in my canvas but when i check my console i get this error and the background does not show:

"game.js:60 Uncaught InvalidStateError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The HTMLImageElement provided is in the 'broken' state. "

The function StartGame is linked in HTML body onload.

Is there anyone who knows how i could fix this?

Thanks :)

Here's my JSFIDDLE:

[http://jsfiddle.net/Nielsvangils/v9hL9d3k/8/][1]

HTML:

<html>
<head>
    <title>Game</title>
</head>
<body onload="startGame()">
    <canvas id="gamefield" width="800" height="600" style="border:1px solid #000000"></canvas>
    <script src="game.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.0.min.js"></script>
    <p>Jump: press <b>SPACE</b></p>

</body>
</html>

Javascript:

var canvas = document.getElementById("gamefield");
ctx = canvas.getContext("2d");

    var background = new Image();
    background.src = "images/gamingbackground2.png";
    function startGame()
    {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(background,0,0);   
    }
  • Please post the relevant code here (in the question). – hindmost May 13 '16 at 10:03
  • 2
    You need to wait for the image to load. Setting the src only starts the loading. The image is not available until its onload event fires or the property complete is set to true. – Blindman67 May 13 '16 at 10:52

0 Answers0