Canvas Draw Rectangles

You are Here:

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
xSpecifies the x-axis coordinate of the rectangle's starting point.
ySpecifies the y-axis coordinate of the rectangle's starting point.
widthSpecifies the rectangle's width.
  • Positive values are to the right
  • Negative values are to the left.
heightSpecifies 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>

Reminder

Hi Developers, we almost covered 93% of Canvas Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in Canvas.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author