HTML | Canvas Draw Bezier Curve

Curves on HTML canvas can be drawn using arcs, but drawing a complex diagram using arcs is quite a tedious task. In the given circumstance, Bezier curve will be very useful in providing more flexibility in drawing curves. Bezier curves on HTML canvas are drawn using a start point, one or more control point/points and an endpoint. Example: In the case of drawing a landscape, real-world objects, irregular shapes etc.
Bezier Curves can be drawn in two ways:

• Quadratic Bezier Curve
• Cubic Bezier Curve

Quadratic Bezier Curve: This curve is controlled by one control point.

Syntax:

moveTo(start_pnt_X, start_pnt_Y);
context.quadraticCurveTo(cntrl_pnt_X, cntrl_pnt_Y, end_pnt_X, end_pnt_y);

Example: This example create a curve using quadratic bezier curve.

Output: Explanation:

• Pre-requisite: HTML Canvas Basics
• First Line: Reference for canvas object is stored in variable ‘c’ using DOM concept.
Second Line: Without having drawing context of canvas nothing can be drawn on it.

var c = document.getElementById("CanvasOfGeeks");
var context = c.getContext("2d");

• One can change the width of line by overriding the value of “lineWidth” attribute of context object.
context.lineWidth=3;
• For putting a dot over the coordinate of control point.You can see the dot in the figure shown above.
context.strokeText( ".", cntrl_pnt_X, cntrl_pnt_Y);
• This function is used to draw a curve from the start point mentioned in function.
context.quadraticCurveTo(cntrl_pnt_X, cntrl_pnt_Y, end_pnt_X, end_pnt_Y);
• This function is used to move the context.
context.moveTo(start_pnt_X, start_pnt_Y);

Note: Please keep the control point within the canvas boundary.

Cubic Bezier Curve: This curve is controlled by two control points.

Syntax:

moveTo(start_pnt_X, start_pnt_Y);
contex.bezierCurveTo(cntrl_pnt_1_X, cntrl_pnt_1_Y, cntrl_pnt_2_X,
cntrl_pnt_2_Y, end_pnt_X, end_pnt_y);

Example: This example create a curve using cubic bezier curve.

                        Cubic Bezier Curve

Cubic Bezier Curve

Output: Example: This example draw a fish using Bezier Curve.
Input:

                   Drawing a fish using Bezier Curve

Output: My Personal Notes arrow_drop_up If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.