- HTML5 Canvas Cookbook
- Eric Rowell
- 247字
- 2021-08-27 12:08:04
Drawing a Quadratic curve
In this recipe, we'll learn how to draw a Quadratic curve. Quadratic curves provide much more flexibility and natural curvatures compared to its cousin, the arc, and are an excellent tool for creating custom shapes.

How to do it...
Follow these steps to draw a Quadratic curve:
- Define a 2D canvas context and set the curve style:
window.onload = function(){ var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); context.lineWidth = 10; context.strokeStyle = "black"; // line color
- Position the canvas context and draw the Quadratic curve:
context.moveTo(100, canvas.height - 50); context.quadraticCurveTo(canvas.width / 2, -50, canvas.width - 100, canvas.height - 50); context.stroke(); };
- Embed the canvas tag inside the body of the HTML document:
<canvas id="myCanvas" width="600" height="250" style="border:1px solid black;"> </canvas>
How it works...
HTML5 Quadratic curves are defined by the context point, a control point, and an ending point:
context.quadraticCurveTo(controlX, controlY, endingPointX, endingPointY);
Take a look at the following diagram:

The curvature of a Quadratic curve is defined by three characteristic tangents. The first part of the curve is tangential to an imaginary line that starts with the context point and ends with the control point. The peak of the curve is tangential to an imaginary line that starts with midpoint 1 and ends with midpoint 2. Finally, the last part of the curve is tangential to an imaginary line that starts with the control point and ends with the ending point.
See also...
- Putting it all together: Drawing a jet, in Chapter 2
- Unlocking the power of fractals: Drawing a haunted tree