Canvas is not showing the image with drawImage()

Asked

Viewed 766 times

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 be used : https://raw.githubusercontent.com/gyrostorm/html5-game-dev-series/gh-pages/images/sprite.png

I would like to show only the scenario when calling the function init. Why isn’t this happening?

1 answer

2


Since your script is included after the canvas, you don’t even have to wait for the load of window to draw. But you have to wait 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);
}

Other than that, attention: define the canvas dimensions as attributes of the canvas itself, not in CSS. When you define in CSS, the content is scaled together, as you can see in this example.

  • Perfect! Sanou my doubt. Grateful.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.