Canvas Pattern

Last Updated:

How to Create Pattern

Your browser does not support the canvas element.

To create pattern, follow these steps

  1. canvas - Assigning the canvas element to a variable.
  2. ctx - Assigning the 2d rendering context to another variable by calling the getContext('2d') method.
  3. img - Assigning a blank DOM object for a HTML img element by using the Image class to a variable.
  4. src - Setting the src attribute to the path of a valid image file, you load that image into the image object just as if you set the src attribute of an actual HTML img element.
  5. ptrn - Assigning a pattern with specified image and repetition using createPattern() canvas method to a variable.
  6. fillStyle - Use fillStyle canvas property to specify the pattern to use inside shapes (any shape).
  7. fillRect() - Use fillRect() canvas method to draws a rectangle that is filled according to the current fillStyle.

Example

HTML Online Editor
<!DOCTYPE html> <html lang="en-US"> <body> <canvas id="point" width="200" height="200"> Your browser does not support the canvas element. </canvas> <script> window.onload = function() { var canvas = document.getElementById("point"); var ctx = canvas.getContext("2d"); var img = new Image(); img.src = 'apple.png'; img.onload = function() { var ptrn = ctx.createPattern(img,'repeat'); ctx.fillStyle = ptrn; ctx.fillRect(0, 0, 200, 200); } }; </script> </body> </html>

Syntax

ctx.createPattern(image, repetition)

Attributes Value

ValueExplanation
image Specifies an image to be used as the pattern.
repetition Specifies how to repeat the pattern's image.
  • repeat
  • repeat-x
  • repeat-y
  • no-repeat

Share this Page

Meet the Author