how to use canvas as background in html code example

Example 1: html canvas background

Theres a few ways you can do this. You can either add a background to the canvas you are currently working on, which if the canvas isn't going to be redrawn every loop is fine. Otherwise you can make a second canvas underneath your main canvas and draw the background to it. The final way is to just use a standard <img> element placed under the canvas. To draw a background onto the canvas element you can do something like the following:

Live Demo

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d");

canvas.width = 903;
canvas.height = 657;


var background = new Image();
background.src = "http://www.samskirrow.com/background.png";

// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
    ctx.drawImage(background,0,0);   
}

// Draw whatever else over top of it on the canvas.

Example 2: how to set background image in canvas using javascript

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

Tags:

Html Example