Canvas: fillRect()
The fillRect(x, y, width, height) method draws a filled rectangle on a 2D canvas.
What you will learn
- How the four arguments describe a rectangle
- How
fillStylechanges its color - How the canvas coordinate origin affects placement
Basic example
const context = canvas.getContext('2d'); context.fillStyle = '#2463eb'; context.fillRect(20, 10, 120, 60);The first two values are the top-left position. The last two are width and height. The rectangle is filled using the current fillStyle.
Common mistakes
- Make sure the context exists before calling
fillRect(). - Canvas coordinates start at the top-left, and positive y moves downward.
- Provide an accessible description when the rectangle communicates information.