Sunday 30 June 2013

HTML5 Canvas Pattern Tutorial

To create a pattern with the HTML5 Canvas, we can use the createPattern() method of the canvas context which returns a pattern object, set thefillStyle property to the pattern object, and then fill the shape using fill().  The createPattern() method requires an image object and a repeat option, which can be repeatrepeat-xrepeat-y, or no-repeat.  Unless otherwise specified, the repeat option is defaulted to repeat.

Code Editor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
 
      var imageObj = new Image();
      imageObj.onload = function() {
        var pattern = context.createPattern(imageObj, 'repeat');
 
        context.rect(0, 0, canvas.width, canvas.height);
        context.fillStyle = pattern;
        context.fill();
      };
      imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/wood-pattern.png';
    </script>
  </body>
</html>


No comments:

Post a Comment