Canvas Draw Rectangles

Last Updated:

How to Draw a Rectangle

Your browser does not support the canvas element.

To draw a rectangle, follow these steps

  1. canvas - Assigning the canvas element to a variable.
  2. ctx - Assigning the 2d rendering context to another variable by calling the getContext('2d') method.
  3. rect() - Use rect() canvas method to draw a rectangle shape (object is invisible here).
  4. fill() - Use fill() canvas method to fill the object with the current fillStyle. The default fillStyle color is 'black'.

Example

HTML Online Editor
<!DOCTYPE html> <html lang="en-US"> <body> <canvas id="point" width="200" height="100"> Your browser does not support the canvas element. </canvas> <script> var canvas = document.getElementById("point"); var ctx = canvas.getContext("2d"); ctx.rect(0, 0, 150, 75); ctx.fill(); </script> </body> </html>

Syntax

ctx.rect(x, y, width, height)

Attributes Value

ValueExplanation
x Specifies the x-axis coordinate of the rectangle's starting point.
y Specifies the y-axis coordinate of the rectangle's starting point.
width Specifies the rectangle's width.
  • Positive values are to the right
  • Negative values are to the left.
height Specifies the rectangle's height.
  • Positive values are to the down
  • Negative values are to the up.

How to Custom Color the Rectangle

Your browser does not support the canvas element.

To custom color the rectangle, follow these steps

  1. canvas - Assigning the canvas element to a variable.
  2. ctx - Assigning the 2d rendering context to another variable by calling the getContext('2d') method.
  3. fillStyle - Use fillStyle canvas property to specify the color to use inside shapes (any shape).
  4. fillRect() - Use fillRect() canvas method to draws a rectangle that is filled according to the current fillStyle.

Example

HTML Online Editor
<!DOCTYPE html> <html lang="en-US"> <body> <canvas id="point" width="200" height="100"> Your browser does not support the canvas element. </canvas> <script> var canvas = document.getElementById("point"); var ctx = canvas.getContext("2d"); ctx.fillStyle = "#339933"; ctx.fillRect(0, 0, 150, 75); </script> </body> </html>

Share this Page

Meet the Author