The Bézier curve is a mathematical model to describe smooth curves and the perfect tool for designing vector graphics. All modern digital illustration software include Bézier curve tools allowing the users to draw smooth curves and bends, including Sketch, Illustrator, Photoshop, SketchUp, 3ds Max … you get the point.
Working with Bézier curves in d3.js is in theory the same thing, but where graphical software gives you the visual feedback when drawing the curves, in code we need to work out the math in order to get everything right. In this article I’ll explain the basics behind the Cubic Bézier and how to use them on <path>
elements in SVG.
Let’s start with an empty SVG with the size 500×300 pixels.
For this demonstration, we’ll be using a simple line. In order to add a curve to this line we need to use the <path>
element. Let’s add it to our SVG:
The d
attribute defines its actual path in the SVG coordinate system. Inside the string we see numbers and letters. The most important thing to remember here is that uppercase letters means absolute positions while lowercase means relative to the current position (reading left to right).
We start by placing the original position using the Move command “M” to location [150,150]
and then the Line command “L” to the location [350, 150]
.
For demonstration purposes, I’ll add some markers to show the location of the anchor points.
In order to create a curve like this, we need to understand a bit more of the syntax of the path’s d
attribute.
The Cubic Bézier curve command starts with “C” (or “c” for relative positions) and consists of four coordinates:
- Start position (this one is implied in the SVG syntax)
- Location of first Bézier handle
- Location of second Bézier handle
- End position
The “start position” is wherever the last operation ends, and as in the first example, this is where we moved to using the Move command (“M”).
And after the “C” you can see there are three more locations, where the last one is [350,150]
- the same locations as before.
Here you can see the locations of the Bézier handles.
Here you can what happens if we change the position of one of the Bézier handles.
… or over here on the left.
Try and drag the handles to see what happens.
What’s next?
I’m planning on extending on this and write a guide on how to generate geometric shapes with rounded corners.
If you’ve got any suggestions or feedback, please don’t hesitate give me a shout at jesper.kiledal@gmail.com.