The canvas element has changed everything. We can now draw and animate complex lines, curves and shapes with a few lines of code. Today we’ll look at quadratic curves.
What are quadratic curves?
It’s been a long time since I took a mathematics lesson, so please don’t expect an in-depth 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 then 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.
Enough math — let’s see some code!
The canvas element supports quadratic curves. First, we require a little initialization to get the canvas context and set the default line width and color:
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 quadraticCurveTo() method can now be used to draw a quadratic curve. It takes four arguments:
- the x co-ordinate of the control point (P1)
- the y co-ordinate of the control point (P1)
- the x co-ordinate of the end point (P2)
- the y co-ordinate of the end point (P2)
Finally, we call the stroke() method to complete our curve:
ctx.quadraticCurveTo(250, 100, 400, 250); ctx.stroke();
You’ve done well to get this far, so I’ve created an interactive canvas quadratic curve demonstration page (sorry, it won’t work in IE8 and below). Drag the control point or either end of the line and it’ll generate the code for you.
In my next post, we’ll create some more interesting shapes using bézier curves…
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