Canvas has the following APIs to draw rectangles:
fillRect(x, y, width, height)
: Draws a filled rectangle.
strokeRect(x, y, width, height)
: Draws a rectangular outline.
clearRect(x, y, width, height)
: Clears the specified rectangular area, making it fully transparent.
The and parameters specify the position on the canvas (relative to the origin) of the top-left corner of the rectangle.
Before we start, let’s create the 2D rendering context:
const context = canvas.getContext("2d");
Now, let’s draw a filled rectangle:
context.fillRect(50, 0, 100, 100)
This will start the position of the rectangle from its top-left edge at the = position, and then draw the length to and width to :
Let’s make the rectangle with only it’s outline:
context.strokeRect(50, 0, 100, 100)
This will draw the previous rectangle, but now only it’s outline is shown:
We can clear a section of a reactangle with clearRect
. Let’s clear a mid-section of our filled rectangle:
context.fillRect(50, 0, 100, 100)
context.clearRect(60, 10, 80, 80)
This will clear the mid-section of the filled rectangle pixels apart:
Note: Please refer to the following shots for information related to this topic:
-Drawing lines and paths
-Drawing triangles
-Filling paths
-Drawing circles and arcs