EN
JavaScript - fill polygon on canvas element in HTML5 with certain color
8 points
Simple solution:
xxxxxxxxxx
1
context.fillStyle = color;
2
3
context.beginPath();
4
context.moveTo(20, 40); // point 1
5
context.lineTo(70, 150); // point 2
6
context.lineTo(110, 80); // point 3
7
context.lineTo(180, 170); // point 4
8
context.lineTo(150, 70); // point 5
9
context.closePath(); // go back to point 1
10
context.fill();
Using JavaScript it is possible to fill polygon with some color in following way.
In this example it has been shown how to fill polygon with color. Read this article how to only draw polygon border.
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="200" height="200"></canvas>
12
<script>
13
14
var canvas = document.querySelector('#my-canvas');
15
var context = canvas.getContext('2d');
16
17
function fillPolygon(points, color) {
18
if (points.length > 0) {
19
context.fillStyle = color; // all css colors are accepted by this property
20
21
var point = points[0];
22
23
context.beginPath();
24
context.moveTo(point.x, point.y); // point 1
25
26
for (var i = 1; i < points.length; ++i) {
27
point = points[i];
28
29
context.lineTo(point.x, point.y);
30
}
31
32
context.closePath(); // go back to point 1
33
context.fill();
34
}
35
}
36
37
var points = [
38
{x: 20, y: 40},
39
{x: 70, y: 150},
40
{x: 110, y: 80},
41
{x: 180, y: 170},
42
{x: 150, y: 70}
43
];
44
45
fillPolygon(points, 'yellow');
46
47
</script>
48
</body>
49
</html>