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:
var canvas = document.querySelector('#my-canvas');
var context = canvas.getContext('2d');
context.beginPath();
context.rect(10, 10, 100); // rect(x, y, side)
context.stroke();
Practical example
In this section, we present a practical example of how to use rect()
method to draw a square on the canvas.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
#my-canvas { border: 1px solid gray; }
</style>
</head>
<body>
<canvas id="my-canvas" width="200" height="200"></canvas>
<script>
var canvas = document.querySelector('#my-canvas');
var context = canvas.getContext('2d');
function drawSquare(x, y, side) {
context.beginPath();
context.rect(x, y, side, side); // rect(x, y, width, height)
context.stroke();
}
drawSquare(30, 30, 100);
</script>
</body>
</html>