Background images In HTML5 Canvas

Instead of a specific color to fill shapes like rectangles, we can use images. To do this, the canvas context has a createPattern() function that takes two parameters: the image to use as the background, and how the image repeats. The last parameter plays a role in the event that the size of the image is smaller than the size of the figure on the canvas. This parameter can take the following values:

  • repeat: The image is repeated to fill the entire space of the shape
  • repeat-x: Image repeats horizontally only
  • repeat-y: Image repeats vertically only
  • no-repeat: image is not repeated

Let’s draw a rectangle and display the image in it:

<!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Canvas in HTML5</title>
        <canvas id="myCanvas" width="300" height="200"
                style="background-color:#eee; border:1px solid #ccc;">
            Your browser does not support Canvas

To use an image, we need to create an Image element and set the source of the image to a local file or a resource on the network:

var img = new Image();

In this case, it is assumed that in the same folder as the html file, I have the image file lamp.jpg . However, it may take some time for the image to load, especially if the image file is taken from the Internet. Therefore, to be sure that the image has already loaded, all actions for using it are performed in the method img.onload, which is called when the image is loaded:

img.onload = function() {
    var pattern = context.createPattern(img, "repeat");
    context.fillStyle = pattern;
    context.fillRect(10, 10, 150, 150);
    context.strokeRect(10, 10, 150, 150);

The method createPattern()returns an object that is set as the fill style of the shape: context.fillStyle = pattern;. The drawing of the rectangle remains the same.