HTML5 Game - Creating and Filling a Pattern

Introduction

To use pattern filling, use the drawing context's createPattern() method.

The set the fillStyle property to the newly created pattern.

The following code shows how you create a pattern.

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html lang="en">
 <head> 
   <script src="https://code.jquery.com/jquery-2.1.3.js"></script> 
  <meta charset="UTF-8"> 
  <title>HTML5 Canvas</title> 
  <script type="text/javascript">
    window.onload = function(){/*from  w  w  w  . j  a  v a2 s. c  o m*/
        let canvas = document.getElementById("myCanvas");
        let context = canvas.getContext("2d");
        // draw stuff here
      let img = new Image(); 
      $(img).load(function () { 
         let pattern = context.createPattern(img, "repeat"); 
         context.fillStyle = pattern; 
         context.fillRect(0, 0, 200, 200); 
       }); 
       img.src = "http://java2s.com/style/download.png"; 
    };
</script> 
 </head> 
 <body> 
  <canvas id="myCanvas" width="300" height="200"></canvas>   
 </body>
</html>

Note

This code creates an Image object for pattern filling.

The first parameter of createPattern() is the image.

The second parameter indicates a repeat direction.

The possible values for the repeat direction are

  • repeat-x (repeat horizontally)
  • repeat-y (repeat vertically)
  • repeat (repeat in both the directions).

The fillStyle property is set to the pattern object.

Related Topic