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.
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.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
#my-canvas { border: 1px solid gray; }
7
8
</style>
9
</head>
10
<body>
11
<canvas id="my-canvas" width=600 height=210> </canvas>
12
<script>
13
14
var canvas = document.querySelector('#my-canvas');
15
var context = canvas.getContext('2d');
16
17
// create image from file
18
var image = new Image ();
19
image.src = 'https://dirask.com/static/bucket/1574890428058-BZOQxN2D3p--image.png';
20
21
image.onload = function() {
22
23
// create pattern object with the image (repeat image)
24
var pattern = context.createPattern (image, 'repeat');
25
26
// set fillStyle value to pattern
27
context.fillStyle = pattern;
28
29
// draw square
30
context.fillRect (0, 0, 200, 200);
31
32
// draw circle
33
context.beginPath();
34
context.arc(275, 160, 40, 0, 2 * Math.PI);
35
context.fill(); // fills circle with pattern
36
context.closePath();
37
38
// write text
39
context.font = '120px sans-serif';
40
context.fillText ('Text', 350, 200); // fillText(text, xStart, yStart);
41
};
42
43
</script>
44
</body>
45
</html>
Image used to create the pattern: