In my previous SVG post we discussed how to create complex diagrams in SVGs using a single <path>. The element has a few other tricks; it offers three smooth curve drawing methods which don’t require an unhealthy knowledge of math or ninja-like coding skills. First, we’re going to examine the quadratic bézier curves.
What are Quadratic Bézier Curves?
Please don’t expect me to provide a comprehensive explanation! If you’re interested, take a look at the migraine-inducing equations at WolframMathWorld…
Like any line, a quadratic curve has a start (P0) and end point (P2). It also has a single control point (P1) which determines the curvature of the line. This image from Wikipedia provides a good curve generation illustration.
Quadratic curves are great for drawing smooth edges. As you can see from this image, it’s easy to specify a control point where the squared edge would normally appear.
Quadratic bézier curves are defined using the ‘Q’ directive in the SVG path ‘d’ attribute:
<path d="M100,250 Q250,100 400,250" />
The initial M directive moves the pen to the first point (100,250). Two co-ordinates follow the ‘Q’; the single control point (250,100) and the final point we’re drawing to (400,250).
You can also use a lowercase ‘q’ to denote relative rather than absolute co-ordinates. The following curve is identical:
<path d="M100,250 q150,-150 300,0" />
Finally, there are shorthand ‘T’ and ‘t’ directives. These accept one co-ordinate which denotes the final point. The control point is assumed to be the same as the last one used, e.g.
<path d="M100,250 Q250,100 400,250 T250,250" />
This draws a curve from 100,250 to 400,250 then 250,250. A single control point at 250,100 is assumed for both.
As usual, the lowercase ‘t’ directive denotes relative rather than absolute co-ordinates.
If you’re finding this a little difficult to visualize, take a look at the interactive SVG quadratic bézier curve demonstration page — it works in all browsers except IE8 and below which don’t support SVGs.
Drag the control point or either end of the curve and the code is generated for you. Click the curve to toggle a fill effect.
In the next SVG post, we’ll use the path element to create more complex cubic bézier curves…