HTML and CSS Reference
• ctx.arcTo(x1, y1, x2, y2, radiusX, [,radiusY, rotation ]) : Adds an arc
between x1,y1 and x2,y2 with the radius defined. It also connects the previous point on the subpath
with a straight line to x1,y1 . If radiusY and rotation are provided, arcTo draws a portion of an
ellipse that has been rotated rotation radians counterclockwise from the positive x axis.
• ctx.arc(x, y, radius, startAngle, endAngle [, anticlockwise ] ) : This
draws an arc starting at x,y of the passed in radius between startAngle and endAngle (defined in
radians). If anticlockwise is set to true , the arc will be drawn counterclockwise.
• ctx.ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle,
anticlockwise) : This draws the portion of an ellipse between startAngle and endAngle start-
ing at x and y with the given radii whose semi-major axis is rotated rotation radians counterclockwise
from the positive x-axis. It connects any previous point on the subpath to the start of the drawn ellipse
• ctx.rect(x, y, w, h) : This draws a new subpath rectangle consisting of four points defined as
the corners of the rectangle and closes that subpath. Similar to fillRect or strokeRect but it gen-
erates a subpath instead.
As you can see, there are lots of ways to draw vector paths. After a path is drawn on the canvas, however, it
is converted into pixel data, and the details of the path are lost. The spec has been updated to create a new Path
object that can be reused by calling ctx.stroke(path) or ctx.fill(path) , but as of this writing that
element hasn't made it into any browsers.
NOTE Bézier curves are parametric curves commonly used in computer graphics. They are defined by a
start and end point and either one (in quadratic curves) or two control points (in cubic curves). These control
points define the size and shape of the curve between the start and end points.
The equation for a point on a Quadric Bézier curve at a given time t is between 0 and 1 and can be written as
a quadratic vector equation:
P(t) = (1-t) 2 P 0 + 2t(1 - t)P c + t 2 P 1
var x = (1-t)*(1-t)*p0.x + 2*t*(1-t)*pc.x + t*t*p1.x
var y = (1-t)*(1-t)*p0.y + 2*t*(1-t)*pc.y + t*t*p1.y
Given start and end points are p0 and p1 and the control point is pc. The Cubic Bézier equation is even more
involved; luckily the browser handles drawing the curves for you. To get a sense of how the control point af-
fects the arc, check out the file bezier.html in the included code.
Rendering Text on Canvas
As you saw in the title screen in Chapter 1, “Flying Before You Walk,” Canvas also has the capability to render
text onto the canvas element. Much like a rectangle drawing, Canvas provides two methods to render text:
ctx.fillText(str, x, y);
ctx.strokeText(str, x, y);
The first method, fillText , draws a string of text with the characters fill-in (as text normally is) at the
location x, y whereas the second, strokeText , draws only the outline. By default the text is aligned to the