EN
JavaScript - draw rectangle on canvas element
0 points
In this article, we would like to show you how to draw a rectangle on an HTML canvas element using JavaScript.
Quick solution:
xxxxxxxxxx
1
var canvas = document.querySelector('#my-canvas');
2
var context = canvas.getContext('2d');
3
context.beginPath();
4
context.rect(10, 10, 150, 100); // rect(x, y, width, height)
5
context.stroke();
In this section, we present a practical example of how to use rect()
method to draw a rectangle on the canvas.
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 drawRectangle(x, y, width, height) {
18
context.beginPath();
19
context.rect(x, y, width, height);
20
context.stroke();
21
}
22
23
drawRectangle(10, 10, 150, 100);
24
25
</script>
26
</body>
27
</html>