dynamic background html5 canvas

Create dynamic canvas image backgrounds websites with HTML5 canvas

Dynamic background image with CSS and an HTML5 canvas. In this post you will find the JavaScript source code used to create a dynamic background for your website.

HTML5 canvas drawing basics

Wouldn't it be nice if you could create a dynamic canvas image background for your website only by writing a few lines of code? If your answer is yes, then please read on. HTML5's canvas offers the possibility of drawing and then exporting the result as inline image information. So, in this post I will show you how you can get from an HTML5 canvas to a background image that you can set as a CSS background image for your website. It will be a dynamic background as you can change the image slightly every time you draw it. Here's the code that produces the dynamic background. If you press "RERUN" you will see that the pattern will change. Below you will find the code explained. I would like to note that this post is not about how to change the HTML canvas background image (drop me a comment in the comments area to let me know if this would be an interesting subject for you). To use HTML5's canvas component for drawing you have to first create it. You can either have the <canvas> tag in your HTML document or you can use JavaScript to create it in memory. Once created you have to get the 2D context of the canvas which provides means of drawing onto the canvas. So, here's the basic code you need to create a canvas dynamically in memory and start drawing on it.
<!DOCTYPE html>

<html>
<head>
<script type="text/javascript">
//create the canvas element
var myCanvas = document.createElement("canvas");

//set the canvas width and height
myCanvas.width=100;
myCanvas.height=100;

//get the 2-dimensional drawing context
var ctx = myCanvas.getContext("2d");

//draw stuff using the ctx
.....
</script>
</head>
<body>
.....
</body>
</html>
To quickly go over the code above, you will first notice the DOCTYPE directive which indicates that this is an HTML5 document. Next we have a JavaScript section in which we first create our canvas element. Please note that the createElement function will create the canvas element in memory and not in the document, so it will not be visible on the screen (unless you append it somewhere in the document). We also have to set the height and width of the canvas, so I did at 100x100 pixels. In our case this will be enough as we will want to create an image 100x100 pixels which we will use for our dynamic background and we will tile this image. To actually draw on the canvas we have to retrieve the canvas' 2D context. This will allow us to draw things like lines, shape contours, filled shapes, etc.

HTML5 canvas - draw an image

Ok, let's start drawing our soon to be dynamic background image. We will draw a 100x100 pixels image which we will tile on our background, so ideally the pattern will be seamless. So, the easiest thing we can do is to have 10x10 squares of 10x10 pixels each and with various shades of gray. What we aim for is a dynamic image looking similar to this: dynamic html5 canvas image To draw squares filled with a gray color we will use the 2d context to draw a rectangle and then fill that rectangle with the right color. Here's the code extract for drawing a rectangle:
...
//prepare a rectangle 10x10 pixels 
//starting from 0,0 coordinates of the canvas
ctx.rect(0,0,10,10);

//set the color you want to use for filling the rectangle
ctx.fillStyle="#cccccc";

//fill the rectangle
ctx.fill();
...
We will want to draw 100 such rectangles one next to the other to cover the entire canvas of 100x100 pixels. Also, we will want to use different shades of gray, so we will do the following:
  1. create an array to store several gray shades which we will later use to randomly pick from
  2. with an iteration draw the 100 rectangles and fill them with a random shade of gray
...
//first we clear the canvas
ctx.clearRect(0,0,100,100);
//setup the palette array
var grayPalette = ["#aaaaaa","#bbbbbb","#cccccc","#dddddd","#eeeeee"];

//create 10x10 squares
for (i=0;i<10;i++){
 for(j=0;j<10;j++){
  //indicate when starting drawing a rectangle
  ctx.beginPath();
  ctx.rect(0+10*j,0+10*i,10,10);

  //choose a random color from the palette
  var randomColorIndex = 
    Math.round(Math.random() * (grayPalette.length-1));
  ctx.fillStyle = grayPalette[randomColorIndex];

  //fill the rectangle with the selected color
  ctx.fill();

  //draw a white border for the rectangle
  ctx.strokeStyle = "#ffffff";
  ctx.stroke();

  //indicating when finished drawing the rectangle
  ctx.closePath();
 }
}
...

CSS dynamic background image

So, we did our drawing on the canvas, the canvas is still in memory. We now have to convert the canvas content to an image that we can use for the dynamic background of our document. The HTML5 canvas component offers the possibility of converting the canvas to URL data. URL data is a way of representing the image binary data encoded such that you can embed it inline in the document and the browser will render it as an image. To get the canvas background image data we need to use the toDataURL() function. We will use the result of this function as the dynamic background image for the body element. Since CSS only supports a static image for the background image style, we will have to dynamically set the backround-image style property using JavaScript. The code will look something like this:
...
var imageDataURL = myCanvas.toDataURL();
//set the resulting image as the background texture
document.body.style.background = 
      "transparent url('"+imageDataURL+"') repeat";

Putting it all together

We now have all we need to create and use our dynamic background. In order to see it work I've included the following code in this page so every time you click this link the background will be dynamically changed (update: I have removed this functionality and extended the post with CodePen examples for dynamically changing the background) Here's the full code needed to set the dynamic background (every time you execute this the background will look different due to the random picking of the squares color):
<!DOCTYPE html>

<html>
<head>
<script type="text/javascript">
//create the canvas element
var myCanvas = document.createElement("canvas");

//set the canvas width and height
myCanvas.width=100;
myCanvas.height=100;

//get the 2-dimensional drawing context
var ctx = myCanvas.getContext("2d");
//first we clear the canvas
ctx.clearRect(0,0,100,100);
//setup the palette array
var grayPalette = ["#aaaaaa","#bbbbbb","#cccccc","#dddddd","#eeeeee"];

//create 10x10 squares
for (i=0;i<10;i++){
 for(j=0;j<10;j++){
  //indicate when starting drawing a rectangle
  ctx.beginPath();
  ctx.rect(0+10*j,0+10*i,10,10);

  //choose a random color from the palette
  var randomColorIndex = 
    Math.round(Math.random() * (grayPalette.length-1));
  ctx.fillStyle = grayPalette[randomColorIndex];

  //fill the rectangle with the selected color
  ctx.fill();

  //draw a white border for the rectangle
  ctx.strokeStyle = "#ffffff";
  ctx.stroke();

  //indicating when finished drawing the rectangle
  ctx.closePath();
 }
}

//this will run when the document has finished loading
function setDynamicBackground(){
  //generate the image from the canvas
  var imageDataURL = myCanvas.toDataURL();

  //set the dynamic image as the background
  document.body.style.background = 
   "transparent url('"+imageDataURL+"') repeat";
}
</script>
</head>
<body onload="setDynamicBackground()">
.....
</body>
</html>

Congratulations

In this post you have actually learned how to use canvas as a background for body. As you can imagine, you can change the code for generating the background to whatever you want. Hope you enjoyed this post and let me know if you have any remarks or questions. If you are interested in drawing with JavaScript you should definitely check out this simple piechart example using JavaScript.

John Negoita

View posts by John Negoita
I'm a Java programmer, been into programming since 1999 and having tons of fun with it.

8 Comments

  1. KoreyMay 16, 2014

    This is very useful. Thanks for this tutorial. The background looks much better. Good Job!

    Reply
  2. RemcoSeptember 4, 2014

    Hey John,

    I use part of this code to generate a lot of pixels. It all works like a charm but I can’t figure out why you use the “0+” in “ctx.rect(0+10*j,0+10*i,10,10);”

    The code seems to work just fine without the “0+”.

    It drives me nuts 🙂 please enlighten me.

    Reply
    1. John NegoitaOctober 15, 2014

      Glad to hear you put this to good use. The “0+” is just a habit of mine when writing code involving matrix data. In this case you can replace the 0 with the offset for the rectangles.

      Reply
  3. GregoryJune 21, 2016

    John thanks for this script. Right now I’m wondering how to use this background in an isolated area on the page like a div or span.

    Reply
    1. John NegoitaJune 21, 2016

      Hi Gregory,

      it’s very easy to do it of a span or div. Instead of doing document.body.style.background=... you need to set the style on the div/span you want document.getElementById("idOfTheElement").style.background=...

      Reply
  4. Luis SalgadoJune 23, 2016

    I have a slightly different implementation of this. Is there any way I can change it to where the image will change size based on the changing of the window size?

    Reply
    1. John NegoitaJune 23, 2016

      Hi Luis,

      yes, that is possible. You need to do something like:

      var onresize = function() {
      width = document.width;
      height = document.height
      //then here create the canvas with the height/width according to what you need
      //and set the style on the body element
      }
      window.addEventListener(“resize”, onresize);

      hope this helps

      Reply
  5. […] Besides using the canvas image data in the src you can also use it as the background CSS property. If you want to learn more about that make sure you read my post Create dynamic backgrounds for websites using HTML5 canvas. […]

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top