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.
- How to Create a Curve Text using CSS3/Canvas ?
- How to draw with mouse in HTML 5 canvas ?
- PHP | ImagickDraw bezier() Function
- CSS | cubic-bezier() Function
- p5.js | bezier() function
- PHP | GmagickDraw bezier() Function
- How to Draw Graphics using Canvas in HTML5 ?
- p5.js | curve() function
- D3.js lineRadial.curve() method
- D3.js line.curve() method
- D3.js areaRadial.curve() Method
- D3.js area.curve() Method
- How to Draw a Half Moon using HTML and CSS?
- How to Draw a Semi-Circle using HTML and CSS ?
- How to Draw a Trapezium using HTML and CSS ?
- How to Draw a Pentagon using HTML and CSS?
- HTML | Canvas Basics
- How to resize an image in an HTML 5 canvas ?
- HTML | canvas lineWidth Property
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.