Bezier Curves
Bezier curves, which are far more flexible than arcs, come in both the cubic and quadratic types:
The Bezier curve is defined in 2D space by a “start point,” an “end point,” and one or two “control” points, which determine how the curve will be constructed on the canvas. A normal cubic Bezier curve uses two points, while a quadratic version uses a single point.
The quadratic version, shown in Figure 2-8, is the simplest, needing only the end point (last) and a single point in space to use as a control point (first):
context
.
moveTo
(
0
,
0
);
context
.
quadraticCurveTo
(
100
,
25
,
0
,
50
);
Figure 2-8. A simple quadratic Bezier curve
This curve starts at 0,0
and
ends at 0,50
. The point in space we
use to create our arc is 100,25
. This
point is roughly the center of the arc vertically. The 100
value for the single control point pulls
the arc out to make an elongated curve.
The cubic Bezier curve offers more options because we have two control points to work with. The result is that curves—such as the classic “S” curve shown in Figure 2-9—are easier to make:
context
.
moveTo
(
150
,
0
);
context
.
bezierCurveTo
(
0
,
125
,
300
,
175
,
150
,
300
);
Figure 2-9. A Bezier curve with two control points
Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.