Hello,

I am trying to load a background image onto my canvas without having it show up on the page itself.
So I've defined a bg parameter and applied the local resource to it, and then tried to use the drawImage method to apply it to the canvas, but nothing seems to happen. Can anyone tell me what am I doing wrong?

Here's the code I am using:

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>New Web Project</title>
        <script>
        var boardTiles;
//        main;

//          function main()
//          {
                //load the board bg image
                var bg;
                bg.src='board.png';

                //display the board image on the canvas
                var c=document.getElementById("gameCanvas");
                var gameBoard=c.getContext("2d");
                gameBoard.drawImage(bg,0,0);

//          }

        </script>
    </head>
    <body>
        <canvas id="gameCanvas" width="1280" height="720" style="border:1px solid #c3c3c3;">
            Your browser does not support HTML5.
        </canvas>

    </body>
</html>

Recommended Answers

All 6 Replies

Try this...

 <canvas id="gameCanvas" width="1280" height="720">
      Your browser does not support HTML5.
 </canvas>

 <script>
 var c = document.getElementById("gameCanvas");
 var gameBoard = c.getContext("2d");
 var bg = new Image();
 bg.onload = function () {
      gameBoard.drawImage(bg, 0, 0);
 };

 bg.src = 'board.png'
 </script>

If you still get nothing, use your browser dev tools-->console to see if there are any errors. Maybe you need to check the path for the image?

hmmm I thought i replied, but i dont see it here. Nevermind:

So thanks a lot, it workedd (I also moved the script into a function and called it to make sure it actually starts), hwever I still don't 100% understand the essence of the change, specifically the "bg.onload = function" part. would be happy if someone could explain itt to a noob.

In the example I provided an image was created dynamically and I used the onload event to execute the function. You wouldn't want to try to draw the image until the image is actually loaded.

Many thanks, again.
So a questoin follows that, is there a way to postpone a function until after all the resources (images, audio) have been loaded?

I'm fairly confident that if you use the javascript onload() method, that will ensure that the page is fully loaded. This is what I have already read and used in my projects.

window.onload=function()
{
    // your javascript code
};

Many thanks, again!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.