HTML Canvas - Rectangles



Rectangle is a simple 2D shape consisting of 4 sides, corners and right angles. Opposite sides of the rectangle have same length and one pair is bigger than the other.

The interface CanvasRenderringContext2D provides properties and methods to render 2D graphics such as rectangles onto the drawing surface of Canvas element. It can be used for drawing shapes as well as styling them on the <canvas> element.

Properties

The properties available to draw rectangles inside the Canvas element are given in the below table.

S.No Property and Description
1 fillStyle

This property can be used to fill the shape drawn onto canvas and specifies the color, gradient or pattern used. The input of this property is all coloring values.

2 strokeStyle

This property applies color, gradient or pattern to the stroked shapes inside Canvas element.

Methods

Following are the various methods available to draw various shapes on HTML Canvas −

S.No Method & Description
1 clearRect()

This method erases all the pixels in the given rectangular area by parameters.

2 fillRect()

This method draws a filled rectangle with the given dimensions inside Canvas element.

3 getContextAttributes()

This method creates an object containing context parameters of the available canvas. To fetch and display this data, we use console or window alerts.

4 rect()

The constructor method rect() is used to add rectangle to the current path.

5 strokeRect()

This method draws a stroked rectangle with the given dimensions inside Canvas element.

Advertisements