EN
JavaScript - draw point on canvas element
10 points
In this article, we would like to show how to draw points on canvas element using JavaScript.

To draw squared points we can use fillRect()
method.
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
function drawPoint(context, x, y, label, color, size) {
15
if (color == null) {
16
color = '#000';
17
}
18
if (size == null) {
19
size = 5;
20
}
21
var radius = 0.5 * size;
22
// to increase smoothing for numbers with decimal part
23
var pointX = Math.round(x - radius);
24
var pointY = Math.round(y - radius);
25
context.beginPath();
26
context.fillStyle = color;
27
context.fillRect(pointX, pointY, size, size);
28
context.fill();
29
if (label) {
30
var textX = Math.round(x);
31
var textY = Math.round(pointY - 5);
32
context.font = 'Italic 14px Arial';
33
context.fillStyle = color;
34
context.textAlign = 'center';
35
context.fillText(label, textX, textY);
36
}
37
}
38
39
40
// Usage example:
41
42
var canvas = document.querySelector('#my-canvas');
43
var context = canvas.getContext('2d');
44
45
drawPoint(context, 20, 30, 'A', 'red', 1);
46
drawPoint(context, 50, 120, 'B', 'blue', 2);
47
drawPoint(context, 140, 70, 'C', 'orange', 5);
48
49
</script>
50
</body>
51
</html>
To draw rounded points we can use arc()
method.
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
function drawPoint(context, x, y, label, color, size) {
15
if (color == null) {
16
color = '#000';
17
}
18
if (size == null) {
19
size = 5;
20
}
21
// to increase smoothing for numbers with decimal part
22
var pointX = Math.round(x);
23
var pointY = Math.round(y);
24
context.beginPath();
25
context.fillStyle = color;
26
context.arc(pointX, pointY, size, 0 * Math.PI, 2 * Math.PI);
27
context.fill();
28
if (label) {
29
var textX = pointX;
30
var textY = Math.round(pointY - size - 3);
31
context.font = 'Italic 14px Arial';
32
context.fillStyle = color;
33
context.textAlign = 'center';
34
context.fillText(label, textX, textY);
35
}
36
}
37
38
39
// Usage example:
40
41
var canvas = document.querySelector('#my-canvas');
42
var context = canvas.getContext('2d');
43
44
drawPoint(context, 20, 30, 'A', 'red', 1);
45
drawPoint(context, 50, 120, 'B', 'blue', 1.7);
46
drawPoint(context, 140, 70, 'C', 'orange', 5);
47
48
</script>
49
</body>
50
</html>