Languages
[Edit]
EN

JavaScript - create pattern

0 points
Created by:
Imaan-Morin
1009

In this article, we would like to show you how to create a pattern to fill the HTML canvas element using JavaScript.

Practical example

In this example, we create a pattern object from an image and use this object as a value for the fillStyle property. Additionally, we draw some objects filled with the pattern using fillRect(), a fill() path, and fillText() methods.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    #my-canvas { border: 1px solid gray; }

  </style>
</head>
<body>
  <canvas id="my-canvas" width=600 height=210> </canvas>
  <script>

    var canvas = document.querySelector('#my-canvas');
    var context = canvas.getContext('2d');

    // create image from file
    var image = new Image ();
    image.src = 'https://dirask.com/static/bucket/1574890428058-BZOQxN2D3p--image.png';

    image.onload = function() {

        // create pattern object with the image (repeat image)
        var pattern = context.createPattern (image, 'repeat');

        // set fillStyle value to pattern
        context.fillStyle = pattern;

        // draw square
        context.fillRect (0, 0, 200, 200);

        // draw circle
        context.beginPath();
        context.arc(275, 160, 40, 0, 2 * Math.PI);
        context.fill(); // fills circle with pattern
        context.closePath();

        // write text 
        context.font = '120px sans-serif';
        context.fillText ('Text', 350, 200);  // fillText(text, xStart, yStart);
    };

  </script>
</body>
</html>

Image used to create the pattern:

See also

  1. JavaScript - draw square on canvas element

  2. JavaScript - draw circle on canvas element

References

  1. CanvasRenderingContext2D.createPattern() - Web APIs | MDN

Alternative titles

  1. JavaScript - create pattern to fill HTML canvas element
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - HTML5 canvas tutorial

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join