Summary: in this tutorial, you’ll learn how to use the JavaScript strockRect() method to draw an outlined rectangle on a canvas.
Introduction to the JavaScript strokeRect() method
The strokeRect() is a method of the 2D drawing context. The strokeRect() allows you to draw an outlined rectangle with the stroke style derived from the current strokeStyle property.
The following shows the syntax of the strokeRect() method:
ctx.strokeRect(x, y, width, height);Code language: CSS (css)In this syntax:
xis the x-axis coordinate of the starting point of the rectangle.yis the y-axis coordinate of the starting point of the rectangle.widthis the rectangle’s width. It can be positive or negative. If thewidthis positive, the method draws the rectangle from (x,y) to the right. Otherwise, it draws the rectangle from the (x,y) to the left.heightis the rectangle’s height. And the height can also be positive or negative. If it’s positive, the method draws the rectangle from the(x,y)to the bottom. Otherwise, it draws the rectangle from the(x,y)to the top.
The strokeRect() draws directly to the canvas without modifying the current path. It means that any subsequent fill() or stroke() call will have no effect.
The JavaScript strokeRect() example
The following shows the index.html page that contains a canvas element:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript strokeRect</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h1>JavaScript strokeRect() Demo</h1>
<canvas id="canvas" height="400" width="500">
</canvas>
<script src="js/app.js"></script>
</body>
</html>Code language: HTML, XML (xml)In the app.js file, define a function that draws two outlined rectangles:
function drawOutlinedRects() {
const canvas = document.querySelector('#canvas');
if (!canvas.getContext) {
return;
}
const ctx = canvas.getContext('2d');
ctx.strokeStyle = 'red';
ctx.strokeRect(100, 100, 150, 100);
ctx.strokeStyle = 'green';
ctx.strokeRect(200, 150, -150, -100);
}
drawOutlinedRects();Code language: JavaScript (javascript)The following picture shows the output: