How to Draw Quadratic Curves on an HTML5 Canvas
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…