Freelance Web Developer

Say Hi

Aug 9, 2010

Drawing Basic Shapes with Canvas

Canvas is a new HTML5 element which can be used to draw graphics using JavaScript. It can be used to draw graphs, make photo compositions or to create cool animations. canvas was first introduced by Apple for the Mac OS X Dashboard. And now is part of the HTML5.
In this article you will learn How to draw basic shapes(Rectangles,paths,Lines and Arcs) with canvas and JavaScript.


In this tutorial I will try to describe how to implement the canvas element in your own HTML pages and How you can draw basic shapes using Jquery.


Before starting the drawing, we need to know about the canvas grid or coordinate. Normally 1 unit in the grid is equal to 1 pixel on the canvas. The origin is positioned in the top left corner (coordinate (0,0)). All elements are placed relative to this origin.

Drawing Rectangles on Canvas

There are three functions that draw rectangles on the canvas:
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 area and makes it fully transparent

Besides these three methods, we also have a method rect which adds a rectangular path to the path list.

rect(x, y, width, height)

View this example

Drawing paths on canvas

To make shapes using paths, there are some methods-
stroke() OR fill()

The first step is calling the beginPath method.
The second is calling the methods that actually specify the paths to be drawn(arc etc).
The third, would be to call the closePath method. that close the shape by drawing a straight line from the current point to the start.
The final step will be calling the stroke and/or fill methods. stroke is used to draw an outlined shape, while fill is used to paint a solid shape.

moveTo Function

This function is like lifting a pen from one point and placing it on the next point.
moveTo(x, y)

View this example

Drawing Lines on canvas

This method can be used to draw straight line.
lineTo(x, y)

x and y are the coordinates of the line's end point.End point of the previous path is the starting point for the following, etc. You can set The starting point by using the moveTo method.

View this example

Drawing Arcs on canvas

arc(x, y, radius, startAngle, endAngle, anticlockwise)

This method takes five parameters: x and y are the coordinates of the circle's center. The startAngle and endAngle parameters define the start and end points of the arc in radians. The angles are measured from the x axis. The anticlockwise parameter is a Boolean value which when true draws the arc anticlockwise, otherwise in a clockwise direction.

Note : Angles are measured in radians, not degrees. To convert degrees to radians you can use the following JavaScript expression:

var radians = (Math.PI/180)*degrees.

View this example

Labels: , ,

By :