Canvas is not showing image with drawImage ()

0

I have an index.html with the following code:

<!DOCTYPE html>
<html>
<head>
    <title> HTML 5 - Airplane Game</title>
    <link rel="stylesheet" href="gamestyle.css"/>
</head>
<body>

    <canvas id="canvasBg">Your Browser does not support HTML5</canvas>
    <script type="text/javascript" src="game.js"></script>
</body>
</html>

And a style in my css:

#canvasBg {
    width: 800px;
    height: 500px;
    display: block;
    margin: 100px auto;
    background-color: #606060;
}

And here's my JS code:

var canvas = document.getElementById("canvasBg");
var ctxBg = canvasBg.getContext('2d');

var imgSprite = new Image();
imgSprite.src = "img/sprite.png";

window.addEventListener("load",init,false);

function init() {
   ctxBg.drawImage(imgSprite,0,0,1600,500,0,0,1600,500);
}

Image to use: link

I would like to show only the scenario when calling the init function. Why is not this happening?

    
asked by anonymous 26.07.2014 / 00:32

1 answer

2

Since your script is included after the canvas, you do not even have to wait for the load of window to draw. But you need to wait for load of the image:

var canvas = document.getElementById("canvasBg");
var ctxBg = canvas.getContext('2d');

var imgSprite = new Image();
imgSprite.src = "https://raw.githubusercontent.com/gyrostorm/html5-game-dev-series/gh-pages/images/sprite.png";
imgSprite.onload = function() {
    ctxBg.drawImage(imgSprite,0,0,1600,500,0,0,1600,500);
}

Otherwise, be careful: set canvas dimensions as canvas attributes, not CSS. When you set it in CSS, the content is scaled together, as you can see in this example .

    
26.07.2014 / 00:41