In this second part of this tutorial, I am going to discuss how to draw other shapes than a rectangle on a canvas using paths.
Think of a path as a collection of pixels going from a starting point to an ending point. A path can also be composed of subpaths.
Four methods are used when dealing with paths:
beginPath(): To start a new path
closePath(): To close the current path
stroke(): To stroke the path
fill(): To fill the path
When we will draw on the canvas, the default color is black. We can change that by using CSS colors with the two following context properties:
. For instance
would define the filling color as red.Drawing straight lines
Consider these two main methods to draw straight lines:
moveTo(x,y): Starting point of the line we want to draw. Think of this method as lifting the "pencil" to the specified coordinate.
lineTo(x,y): Think of this method as drawing the path from the previous specified point to this one.
Here is how you would draw a path using three lines:
Drawing circles or arcs
To draw a circle or an arc, we are going to use the
arc(x, y, radius, startAngle, endAngle)
y being the coordinates of the center of the circle/arc in pixels
radius being the radius of your circle/arc in pixel
startAngle being the starting angle of the circle/arc in radians
endAngle being the ending angle of the circle/arc in radians
ctx.arc(200,100,50,0,Math.PI*2); //Here for instance, this will represent a full circle.
ctx.fill(); //Again, we have the choice to either draw a filled circle or a stroked circle.
We have seen how to draw shapes and lines made of paths.
- Drawing text is still drawing a path
- Like other shapes we have just discussed, we can have a filled text or stroked text
Let us see how it works:
ctx.textAlign="center"; //is the position of the text regarding to a specified point.
ctx.font="bold 30px verdana"; //has the same syntax as the CSS font rule.
ctx.fillText("Hello World!", 266.5, 150);
has the following arguments: a text string to draw then the x coordinate and the y coordinate of the point where we want to draw the text.
Stay tuned and check out the third part of this tutorial coming soon which will discuss how to draw images on a canvas and how to work with pixels on the canvas.