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.

Syntax:

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

<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='utf-8'>
    <title>Codecrawl.com: Image in canvas</title>
    <style>
        canvas {
            border: 1px solid #000;
        }
    </style>
</head>
<body>
<canvas id='canvas' width='640' height='480'></canvas>
<script>
    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;
        canvas.fill();
    }
        canvasImage.addEventListener('load',createImagePattern,false);
    canvasImage.src = 'https://codecrawl.com/code/images/ushuaia1.jpg';
</script>
</body>
</html>

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

HTML Table: Table background color

This entry is part 14 of 16 in the series HTML Table

To make a particular row or column to stand out in a table, we can put a background color to it.
Output

<!DOCTYPE html>
<html>
<head lang='en'>     
    <meta charset='UTF-8'>
    <title>Codecrawl.com-HTML Table</title>
</head>
<body>

<table style='width: 60%; border-style:solid; border-width: 1px'>
    <tr>
        <th>ID</th>
        <th>artiste</th>
        <th>album</th>
    </tr>
    <tr style='background-color: wheat'>
        <td>1</td>
        <td>Rod Stewart</td>
        <td>Maggie May</td>
    </tr>
</table>

</body>
</html>

HTML: Adding a background picture

This entry is part 21 of 34 in the series HTML

To use a background image file, use a style=’background-image: url(image)’ attribute in the opening <body> tag.

<!DOCTYPE html>
<html>
<head lang='en'>
    <meta charset='UTF-8'>
    <title>HTML colors</title>
</head>
<body style='background-image: url(https://codecrawl.com/code/images/sky.jpg)'>

<h4>I have a backgound picture</h4>

</body>
</html>

By default, the backgound image is repeated both horizontally and vertically to fill the window.

You can force it not to repeat by adding the background-repeat: no-repeat attribute.

<!DOCTYPE html>
<html>
<head lang='en'>
    <meta charset='UTF-8'>
    <title>HTML colors</title>
</head>
<body style='background-image: url(https://codecrawl.com/code/images/sky.jpg); background-repeat: no-repeat'>

<h4>I have a backgound picture</h4>

</body>
</html>