How to draw rectangles in HTML Canvas

Rectangles are some of the simplest shapes that can be drawn on an HTML canvas. In this article, we'll take a look at how to draw rectangles in HTML canvas, with a brief history and some code samples.

Rectangles have been used in art and design for centuries. They are simple and efficient shapes that can be used to create complex images. HTML canvas provides an easy way to draw rectangles.

Rectangles are defined by their width and height. To draw a rectangle in HTML canvas, we first need to create a context and then call the rect() function. The rect() function takes four parameters: the x-coordinate, the y-coordinate, the width, and the height.

Here's an example of how to draw a rectangle:

var canvas = document.getElementById("canvas");

var context = canvas.getContext("2d");

context.rect(10, 10, 100, 100);

This code will draw a rectangle with the top-left corner at (10, 10), the bottom-right corner at (100, 100), and a width of 100 pixels and a height of 100 pixels.

Rectangles can also be filled and/or outlined. We can use the fill() and stroke() functions to do this.

Here's an example that fills and outlines a rectangle:

context.fillStyle = "red";

context.strokeStyle = "black";

context.fillRect(10, 10, 100, 100);

context.strokeRect(10, 10, 100, 100);

This code will draw a red rectangle with a black border.

Rectangles can also be rotated and skewed. We can use the rotate() and skewX() functions to do this.

Here's an example that rotates and skews a rectangle:

context.rotate(30);

context.skewX(10);

context.fillRect(10, 10, 100, 100);

This code will rotate the rectangle by 30 degrees and skew it to the right by 10 degrees.

There are many other things that can be done with rectangles in HTML canvas.