EN
JavaScript - draw polygon on canvas element in HTML5
4 points
In this short article, we want to show how to draw stroke line according indicated points on HTML5 Canvas using JavaScript.

Quick solution:
xxxxxxxxxx
1
context.beginPath();
2
context.moveTo( 20, 40); // point 1
3
context.lineTo( 70, 150); // point 2
4
context.lineTo(110, 80); // point 3
5
context.lineTo(180, 170); // point 4
6
context.lineTo(150, 70); // point 5
7
context.closePath(); // go back to point 1
8
context.stroke(); // draw stroke line
In this we want to show how to draw polygon border.
Note: read this article to see how to fill polygon with certain color.
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
context.beginPath();
18
context.moveTo( 20, 40); // point 1
19
context.lineTo( 70, 150); // point 2
20
context.lineTo(110, 80); // point 3
21
context.lineTo(180, 170); // point 4
22
context.lineTo(150, 70); // point 5
23
context.closePath(); // go back to point 1
24
context.stroke(); // draw stroke line
25
26
</script>
27
</body>
28
</html>
In this we want to show how to create universal method that draws polygon border for provided array of points.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
#my-canvas { border: 1px solid gray; }
7
8
</style>
9
<script>
10
11
function Drawer(canvas) {
12
var context = canvas.getContext('2d');
13
this.drawPolygon = function(points) {
14
if (points.length > 0) {
15
context.beginPath();
16
var point = points[0];
17
context.moveTo(point.x, point.y); // point 1
18
for (var i = 1; i < points.length; ++i) {
19
point = points[i];
20
context.lineTo(point.x, point.y); // point from 2 up to (points.length - 1)
21
}
22
context.closePath(); // go back to point 1
23
context.stroke(); // draw stroke line
24
}
25
};
26
}
27
28
</script>
29
</head>
30
<body>
31
<canvas id="my-canvas" width="200" height="200"></canvas>
32
<script>
33
34
var canvas = document.querySelector('#my-canvas');
35
var drawer = new Drawer(canvas);
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
drawer.drawPolygon(points);
46
47
</script>
48
</body>
49
</html>