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.
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.
- 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.
- 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.
Note: Please keep the control point within the canvas boundary.
Cubic Bezier Curve: This curve is controlled by two control points.
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.
Example: This example draw a fish using Bezier Curve.
- HTML | canvas Tag
- HTML | DOM Canvas Object
- HTML | Canvas Basics
- HTML | canvas scale() Method
- HTML | canvas createLinearGradient() Method
- HTML canvas rotate() Method
- HTML | canvas lineJoin Property
- HTML | canvas translate() Method
- HTML | <canvas> height Attribute
- HTML | canvas fillRect() Method
- HTML | canvas textBaseline Property
- HTML | canvas lineCap Property
- HTML | canvas font Property
- HTML | canvas shadowOffsetY Property
- HTML | canvas strokeRect() Method
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.