To better understand and visualize how a browser interprets a canvas element, it is usually said that a canvas is a two-dimensional grid, with the first dimension being the upper-left corner as a starting point (in pixels) and the second one being the width and height of it (also in pixels).

To draw a canvas object or element, one has to define its coordinates first. For example the coordinate (0, 0) is at the upper-left corner of the canvas; and further, along the x-axis the value increases towards the right edge of the canvas while along the y-axis the value increases towards the bottom edge of the canvas.

Drawing a rectangle

Following methods are basic methods that may be used to draw a rectangle in canvas:

  • getContext("2d") - built-in method that defines the context in which the canvas will be drawn (i.e. "2d")
  • fillStyle - defines the fill color of the element
  • fillRect(x,y,x+,y+) - draws a rectangle defined with the starting point (x,y) and sized with x+ and y+
  • stroke() - strokes the sub paths with the current stroke style.

Example

Example showing how to draw a rectangle with canvas element:

 

›› go to examples ››