The article “How to Create Complex Paths in SVGs” examined the
<path> element and showed how to draw a series of lines and arcs to create any shape. (It’s often used to replicate fonts without requiring a full font download.)
d attribute offers a couple of extra tricks to draw smooth curves. In this article, we’ll discuss cubic Bézier curves, but you can also refer to “How to Draw Quadratic Bézier Curves on SVG Images” for a slightly simpler option.
What are Cubic Bézier Curves?
You’ve possibly encountered cubic Bézier curves in desktop publishing and graphics packages. They define a start point (
P0) and end point (
P3). However, while quadratic curves use one control point, cubic Bézier curves have two: one for each end of the line (
P2). Wikipedia’s Bézier curve page provides a good generation illustration:
The terrifying equations can also be examined at WolframMathWorld.
Cubic Bézier curves provide further possibilities. The two control points can generate curves which reverse direction or wrap around on themselves.
Cubic Bézier curves are defined using the
C directive in the path’s
<path d="M100,250 C100,100 400,100 400,250" />
M directive moves the pen to the first point (
100,250). Three coordinates follow the
C: the first control point (
100,100), the second control point (
400,100), and the final ending point (
You can also use a lowercase
c to denote relative rather than absolute coordinates. The following curve would be identical and is possibly easier to code:
<path d="M100,250 c0,-150 300,-150 300,0" />
Finally, there are shorthand
s directives (as usual, the lowercase option denotes relative rather than absolute coordinates). These accept two further coordinates to string multiple curves together by setting another final point and its associated control point. The starting control point is assumed to be the same as the end control point on the previous curve. For example, take this path:
<path d="M100,250 C100,100 400,100 400,250 S700,400 700,250" />
It draws a curve from
100,250 (control point at
400,250 (control point at
400,100) as above. Another curve is then drawn from
400,250 (control point unchanged at
700,250 (control point at
Cubic Bézier curves can be a little difficult to code and visualize, so this quick generation tool will generate the
<path> code for you:
Drag the control points on either end of the curve accordingly. Click the curve itself to toggle a fill effect which adds an ending
Note that this tool must convert DOM page coordinates to SVG coordinates to ensure it works at all screen sizes. This can be a little more complex than you expect, so refer to “How to Translate from DOM to SVG Coordinates and Back Again” for full details.
If you’d like a slightly easier option, try creating quadratic Bézier curves on SVG images.