What are bézier curves?
You’ve possibly seen bézier curves used in desktop publishing and graphics packages. So let’s take another trip to WolframMathWorld to look at the equations.
I’m sure you understood that but I’m feeling a little nauseous.
In the last post, we saw how quadratic curves have a start point (P0), end point (P2) and a single control point (P1) which determines the curvature. In the case of canvas, a bézier curve has a start (P0), end (P3) and two control points — one for each end of the line (P1 and P2). Thanks again to Wikipedia for a great illustration.
Béziers give far more control over the shape. Because the initial part of the curve follows its control path, we can generate curves which reverse direction or wrap on themselves. They are ideal for creating a Visio-like flow diagram where you need to join two shapes by a connector.
On to the code!
canvas = document.getElementById("canvas"); ctx = canvas.getContext("2d") ctx.lineWidth = 6; ctx.strokeStyle = "#333";
We now define the starting point for our curve (P0):
ctx.beginPath(); ctx.moveTo(100, 250);
The bezierCurveTo() method is then used to draw the curve. It requires six arguments:
- the x co-ordinate of the curve start control point (P1)
- the y co-ordinate of the curve start control point (P1)
- the x co-ordinate of the curve end control point (P2)
- the y co-ordinate of the curve end control point (P2)
- the x co-ordinate of the end point (P3)
- the y co-ordinate of the end point (P3)
Finally, we call the stroke() method to complete our curve:
ctx.bezierCurveTo(150, 100, 350, 100, 400, 250); ctx.stroke();
The interactive canvas bézier curve demonstration page allows you to drag all the points and generate the code (sorry IE fans — you’ll need to wait for IE9).
I hope you found this series useful. Are you using canvas curves for any interesting projects?
Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.
The Principles of Beautiful Web Design, 4th Edition
Docker for Web Developers
Learn PHP in One Day and Learn It Well