Quadratic and Bézier Curves
Canvas also includes functions for creating Quadratic and Bézier curves. These methods are shown below:
quadraticCurveTo(cp1x, cp1y, x, y)
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
If you are new to Quadratic and Bézier curves, they can be difficult to get used to. For both:
- Start with a line with a stated start point and end point.
- The start point is the current position, which you can set using the moveTo(x,y) method.
- The end point is set with the last two arguments of the method: x and y.
- Add control points.
- Just one for a Quadratic curve.
- Two for a Bézier curve.
- Imagine that these control points are tugging at the straight line created by the start and end points. By doing so, they create a curve.
The best way to see how they work is to practice with them a little. We've built small HTML5 applications for doing so.
We'll start with Quadratic curves:
- Open html5-canvas/Demos/quadratic.html in your browser. You will see:
- A 500x500 Canvas.
- A menu in the upper right with as Start Over button for clearing the canvas and controls for setting the color.
- A textarea immediately below the Canvas, which holds the generated code, in case you create a drawing you want to use somewhere else.
- A list of the current curve point values to the right of the textarea.
To use this application:
- Click anywhere on the Canvas to set a start point.
- Click a second time to set an end point.
- Click a third time to set the control point.
- Click a fourth time to start over; that is, to set a start point for a new curve.
You may change the color any time before the fourth click to set a new color for the curve.
Play around with this for a little and then open html5-canvas/Demos/bezier.html in your browser to play with creating Bézier curves. This application is the same, except that the fourth click sets a second control point.
If you generate a drawing you like:
- Open html5-canvas/Demos/test-bed.html in your editor.
- Copy the code from the textarea in the curve application.
- Paste it between the start paste and end paste comments in test-bed.html and save.
- Open test-bed.html in your browser. You should see your drawing there.