EN
JavaScript - create pattern
0
points
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: