Search code examples
javascripthtmlcanvashtml5-canvasbackground-image

How to draw a background image on an HTML5 canvas


I'm working on my first HTML5 Canvas game. I am trying to put in a background image, and I don't know how to do it. The game will change backgrounds throughout levels, but I think I understand how to make that happen. However, if I just try to draw an image, then it appears above my title text. Any ideas how to fix this? I don't think the CSS method will work, because the background will change. Here is my code:

<!DOCTYPE html>
<html>
<head>
  <title>How Well Do You Know Your Swedish?</title>
</head>
<body>
  <canvas width="640" height="480" id="game" style="display: block; margin-left: auto;         margin-right: auto; border: 1px solid black;" Your Browser is not compatible with this game. We recommend Google Chrome, Mozilla Firefox, or Opera.></canvas>
  <script>
    var game_canvas = document.getElementById("game");
    var game_context = game_canvas.getContext("2d");
    var swedishflagbg = new Image();
    swedishflagbg.src = "resources/images/swedishflagbg.png";
    swedishflagbg.onload = function() {
      game_context.drawImage(swedishflagbg, 0, 0);
    }
    game_context.fillStyle = "#000000";
    game_context.font = "35px Ubuntu";
    game_context.textAlign = "center";
    game_context.textBaseline = "top";
    game_context.fillText("How Well Do You Know Your Swedish?", 320, 0);
  </script>
</body>
</html>

I am new to JavaScript, and even newer to the HTML5 Canvas.


Solution

  • Extending from comment:

    The "why":

    Because the background image is drawn in an onload event, which will happen "later", while text is drawn immediately.
    So the text is drawn first, and then sometimes later the image is drawn, thus causing the text to be covered.

    The "how":

    Depending on how "dynamic" the background image is, you can consider:

    1. use CSS background-image on cancas/canvas container, and use className/classList to switch between different backgrounds;
    2. put an <img> tag underneath the canvas, and change its src property;
    3. use an additional "background" canvas underneath the current one, so you can draw the game content in current one, and draw the (probably not frequently-updated) background in the new one.

    Credit of idea 1 and 2 goes to @markE :)