How to Use JavaScript strokeRect to Draw an Outlined Rectangle (original) (raw)

Skip to content

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:

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:

`

JavaScript strokeRect
<h1>JavaScript strokeRect() Demo</h1>

<canvas id="canvas" height="400" width="500">
</canvas>

<script src="js/app.js"></script>
`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:

Here is the strokeRect() demo.

How it works.

Summary

Was this tutorial helpful ?