HTML Canvas Curves
HTML Canvas Curves
The three most used methods for drawing curves in canvas are:
- The
arc()
method (described in Canvas Circles chapter) - The
quadraticCurveTo()
method - The
bezierCurveTo()
method
The quadraticCurveTo() Method
The quadraticCurveTo()
method is used to define a
quadratic Bezier curve.
The quadraticCurveTo()
method has the following parameters:
Parameter | Description |
---|---|
cpx | Required. The x-coordinate of the control point |
cpy | Required. The y-coordinate of the control point |
x | Required. The x-coordinate of the end point |
y | Required. The y-coordinate of the end point |
The quadraticCurveTo()
method requires two
points: One control point and one end point. The starting point is the latest
point in the current path, which can be changed using
moveTo()
before creating the quadratic Bezier curve.
To draw the curve on the canvas, use the following methods:
-
beginPath()
- Begin a path -
moveTo()
- Define the start position -
quadraticCurveTo()
- Define the quadratic Bezier curve -
stroke()
- Draw it
Example
This quadratic Bezier curve begins at the point specified by moveTo(): (10, 100). The control point is placed at (250, 170). The curve ends at (230, 20):
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(10, 100);
ctx.quadraticCurveTo(250, 170,
230, 20);
ctx.stroke();
</script>
Try it Yourself »
The bezierCurveTo() Method
The bezierCurveTo()
method is used to define a cubic Bezier curve.
The bezierCurveTo()
method has the following parameters:
Parameter | Description |
---|---|
cp1x | Required. The x-coordinate of the first control point |
cp1y | Required. The y-coordinate of the first control point |
cp2x | Required. The x-coordinate of the second control point |
cp2y | Required. The y-coordinate of the second control point |
x | Required. The x-coordinate of the end point |
y | Required. The y-coordinate of the end point |
The bezierCurveTo()
method requires three
points: Two control points and one end point. The starting point is the latest
point in the current path, which can be changed using
moveTo()
before creating the cubic Bezier curve.
To draw the curve on the canvas, use the following methods:
-
beginPath()
- Begin a path -
moveTo()
- Define the start position -
bezierCurveTo()
- Define the cubic Bezier curve -
stroke()
- Draw it
Example
This cubic Bezier curve begins at the point specified by moveTo(): (20, 20). The first control point is placed at (110, 150). The second control point is placed at (180, 10). The curve ends at (210, 140):
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.bezierCurveTo(110, 150, 180,
10, 210, 140);
ctx.stroke();
</script>
Try it Yourself »