NaN
Curves I: Bezier Curves
Let's be honest. You wouldn't be reaching for SVG paths if you only wanted to draw straight lines; you'd use an SVG <line />
element instead.
The true power of SVG paths comes from being able to draw curves. So let's talk about curve commands! There are three types of curves you can draw using SVG paths: quadratic bezier curves, cubic bezier curves, and arcs.
We'll divide these conversations into three parts, starting with quadratic bezier curves first.
Bezier Curves
A bezier curve is a curve that is defined by a series of points known as control points. SVG paths support two types of bezier curves — quadratic bezier curves, which have one control point, and cubic bezier curves, which have two control points.
The more control points a curve has, the more complex the curve can be. Try moving the points in the playground and notice that the cubic bezier curve (the bottom curve) has a lot more freedom in its shape when compared to the quadratic curve (the top curve).
Quadratic Curves
While cubic bezier curves are more flexible, quadratic bezier curves are simpler to write, making them preferable when you don't need the extra shape.
The Q
command lets you draw a quadratic bezier curve:
Q controlX controlY endX endY
This curve, for example, creates a rounded corner:
- M5.00.0
- v5.0
- Q5.015.015.015.0
- h5.0
Chaining Quadratic Curves
If you want to write multiple, consecutive quadratic curves, you might be tempted to write something like this:
Q 5 10 10 10
Q 15 10 15 15
While this works just fine, there is an easier way — using the T
command:
- M5.05.0
- Q5.010.010.010.0
- T15.015.0
The T
command will draw a new quadratic curve using the reflection of the previous curve's control point. Try changing the control point of the first curve and notice how it changes the second curve.
Of course, this approach will only work if the reflection point is indeed the point that you're looking for - if it's not, you'll still have to use the full
Q
command.
Practice
Using all of the commands we've looked at so far (cursor, line, and quadratic curve), trace over this little picture frame icon:
(As a little bonus, try rounding the frame!)