Using SVG with CSS3 and HTML5 — Supplementary Material

Example code and online extras for the O'Reilly Media book by Amelia Bellamy-Royds, Kurt Cagle, and Dudley Storey.

Calculating Cubic Béziers

In Chapter 6 in the book, we showed how a quadratic Bézier curve is constructed mathematically from the end points and the control point, by comparing it to a “string art” drawing, as shown in Figure 6-X4.

A shape with two pointed corners and two curved sides, in blue. A series of purple lines wrap around both curved sides, while tracing out the edges of a square with their start and end points.
Figure 6-X4. A quadratic Bézier path, and the string art mesh that encloses it

Cubic Bézier curves are more complicated, starting from the fact that they have two control points for each segment. If you wanted to draw a cubic curve by hand, using the “string art” method, you would need a multi-step process:

The string art diagrams get rather messy for cubic curves, as shown in Figure 6-X5, but the final curves can be very elegant. The dark blue and purple lines show how the quadratic scaffolding was constructed. The thick red strings connect them and sketch out the actual cubic Bézier shape.

Four square figures, arranged in a grid.  Each has a solid, curved shape, with lines wrapped around it. The top-left curve is in a D-shape. The top-right is a stretched S-shape along the diagonal.  Bottom-left is almost triangular, with convex curves joining in a point. Bottom-right is a tear-drop shape in one corner.
Figure 6-X5. Cubic Bézier curves and their “string art” basis

The four curves in Figure 6-X5 are as follows (using a scale with 10 units along each edge of the square, instead of 10cm):

<path d="M 0,0 C 10,0  10,10 0,10"/>
<path d="M 0,0 C 10,0   0,10 10,10"/>
<path d="M 0,0 C 10,10 10,0   0,10"/>
<path d="M 0,0 C  0,10 10,0   0, 0"/>

Each curve has start, end, and control points in different corners of a square; the thin purple and navy strings are used to sketch out the quadratic curves, and then the thick red strings sketch the cubic curve. Nonetheless, for the computer, it is just a weighted average of weighted averages of all the points.

View a live, animated version of the S-curve. You can then change the start point, control points, and end point by editing the s, c1, c2, and e parameters in the URL.