Canvas Pattern

How to Create Pattern

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
imageSpecifies an image to be used as the pattern.
repetitionSpecifies how to repeat the pattern's image.
  • repeat
  • repeat-x
  • repeat-y
  • no-repeat

Reminder

Hi Developers, we almost covered 93% of Canvas Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in Canvas.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Meet the Author