Drawing Bézier curves

Drawing Bézier curves

You can use either the arc() method or the arcTo() method to draw curved lines, but however the arcs produced have only one curved line of the same radius. To be able to fully manipulate our curves we use either the quadraticCurveTo(), or the bezierCurveTo() methods. Don’t be confused by the names of these two methods, they are both Bézier curves. The quadraticCurveTo() is actually a quadratic Bézier curve and the bezierCurveTo() is a actually a cubic Bézier curve.

quadraticCurveTo(controlX, controlY, endPointX, endPointY)

The quadraticCurveTo(controlX, controlY, endPointX, endPointY) method produces a quadratic Bézier curve whose two tangents extend from the context point (current point) to the control point (controlX ; controlY) and from the control point to the endPoint (endPointX ; endPointY) as shown below:

quadratic bezier curve

Now lets see an example on how to use this method. The following code produces a quadratic curve from context point (100; 400) to ending point (300; 400) curved by the control point (200; 200). In other words the quadratic curve produced has the tangents (100; 400) to (200; 200) and (300; 400) to (200; 200).


var canvas = document.getElementById("canvas1");
var context = canvas.getContext('2d');

context.lineWidth = 5;
context.strokeStyle = "blue";

context.moveTo(100, 400);
context.quadraticCurveTo(200, 200, 300, 400);

context.stroke();

Quadratic bezier canvas



bezierCurveTo(cpX1, cpY1, cpX2, cpY2, epX, epY)

Unlike the quadraticCurveTo() method which has one control point, the bezierCurveTo(cpX1, cpY1, cpX2, cpY2, epX, epY) method has two control points, control point1 (cpX1; cpX2) and control point2 (cpX2; cpY2). The arc starts at the context point and ends at the ending point.

Cubic bezier curve

Example code:


var canvas = document.getElementById("canvas1");
var context = canvas.getContext('2d');

context.lineWidth = 5;
context.strokeStyle = "blue";

context.moveTo(100, 250);
context.bezierCurveTo(200,100,400,400,500,250)

context.stroke();

Cubic bezier curve canvas