javascripthtmlhtml5-canvas

Background image javascript HTML5 canvas


I'm trying to create a simple game using javascript to run on a simple webpage. For some reason, I can't get it to load a background image. I've searched repeatedly and tried numerous ways but I ended up with a black-white canvas. Please, help me as I'm at my wits end.

Here's my code snippet:

<body>


<!-- Site navigation menu -->
<ul>
<li><a href="index.html">Play Game</a></li>
<li><a href="about.html">About</a></li>
<li><a href="help.html">Help</a></li>
</ul>


<!-- Creating the canvas -->
<canvas id= "gameCanvas" width="600" height="480"></canvas>

<script>
var canvas = document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
var bkGround = new Image();
bgImage.src = '/images/backGround.jpg';
bkGround.onload = function(){
ctx.drawImage(bkGround,69,50);   
}​
</script>

Anticipated thanks.


Solution

  • I believe that you may be trying to use the background image before has complted loading but you can also use these approaches with CSS.

    You can use CSS and either define in your style block or dynamically set it in JS.

    <style>
    
    #gameCanvas{
        background-image:    url(/images/backGround.jpg);
        background-size:     cover;                      
        background-repeat:   no-repeat;
        background-position: center center;
    }
    </style>
    

    or if prefer in JS:

    document.getElementById("gameCanvas").style.background = "url('/images/backGround.jpg')";
    

    NB - make sure the image is access to the browser. Also check your console for errors if using JS - the JS may be breaking with an error before reaching your code. Also for a working example see HTML5 Canvas background image