HTML5 Canvas: Using an image to fill the canvas background

This entry is part 17 of 17 in the series HTML5 Canvas

The canvas API provides a way for us to fill the background with an image.

Using the createPattern method, you can use an image to fill the background of a shape.


Context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh);

<!DOCTYPE html>
<html lang='en'>
    <meta charset='utf-8'>
    <title> Image in canvas</title>
        canvas {
            border: 1px solid #000;
<canvas id='canvas' width='640' height='480'></canvas>
    var canvas = document.getElementById('canvas').getContext('2d');
    var canvasImage = new Image();
    function createImagePattern() {
        var pattern = canvas.createPattern(canvasImage, 'repeat');
        canvas.rect(0, 0, 640, 480);
        canvas.fillStyle = pattern;
    canvasImage.src = '';

The repeat parameter can have the following values:

  • repeat: Repeats the pattern horizontally and vertically
  • repeat-x: Repeats the pattern horizontally
  • repeat-y: Repeats the pattern vertically
  • no-repeat: Does not repeat the pattern
Series Navigation<< HTML5 Canvas: Cropping an image

Leave a comment

Leave a Reply