EN
JavaScript - draw square on canvas element
0 points
In this article, we would like to show you how to draw a square 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, 100); // rect(x, y, side)
5
context.stroke();
In this section, we present a practical example of how to use rect()
method to draw a square 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 drawSquare(x, y, side) {
18
context.beginPath();
19
context.rect(x, y, side, side); // rect(x, y, width, height)
20
context.stroke();
21
}
22
23
drawSquare(30, 30, 100);
24
25
</script>
26
</body>
27
</html>