Quadratic Curve In Canvas: HTML5

Advertisement:

Today lets learn to draw quadratic curves on Canvas, using HTML5.

index.html and myStyle.css files are kept same as illustrated in previous video tutorial: Canvas State: HTML5

quadratic-curve-canvas-html5

Syntax
quadraticCurveTo(cx, cy, endX, endY);

(cx, cy) are control point.
(endX, endY) are end point of the curve.

You may be wondering about the start point!
We specify it with the help of moveTo() method.

Quadratic curve start at the current pen position using the given control point cx, cy and end at the end points defined by endX, endY.

i.e., Quadratic curves use a starting point, one control point and an end point.

Javascript file: Quadratic Curve
myScript.js

1
2
3
4
5
6
7
8
		context.lineWidth= 6;
		context.beginPath();
		context.moveTo(20, 100);
		context.quadraticCurveTo(80, 190, 150, 120);
		context.strokeStyle= "red";
		context.fillStyle= "yellow";
		context.stroke()
		context.fill();

With a line width of 6px, we draw a line from 20px x-axis, 100px y-axis and using the control point 80px x-axis, 190px y-axis, we join to the end points 150px x-axis, 120px y-axis.

Javascript file: Control Point
myScript.js

1
2
3
4
5
6
7
		context.lineWidth= 1;
		context.beginPath();
		context.moveTo(20, 100);
		context.lineTo(80, 190);
		context.lineTo(150, 120);
		context.strokeStyle = "pink";
		context.stroke();

With the help of the points in Quadratic curve example above, we trace its control points.
moveTo takes the same value.
first lineTo takes control points value.
second lineTo takes end point values of quadratic curves.

Quadratic Curve In Canvas: HTML5


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=OMDfbpLBeGc [Watch the Video In Full Screen.]



Related:
Draw Arcs/Circle with Canvas: HTML5
Bezier Curve In Canvas: HTML5

Javascript file: Full Code
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
window.onload = canvas;
 
function canvas()
{
	var myCanvas = document.getElementById("myCanvas");
 
	if( myCanvas && myCanvas.getContext("2d") ) 
	{
		var context         = myCanvas.getContext("2d");
 
		context.lineWidth= 6;
		context.beginPath();
		context.moveTo(20, 100);
		context.quadraticCurveTo(80, 190, 150, 120);
		context.strokeStyle= "red";
		context.fillStyle= "yellow";
		context.stroke()
		context.fill();
 
		context.lineWidth= 1;
		context.beginPath();
		context.moveTo(20, 100);
		context.lineTo(80, 190);
		context.lineTo(150, 120);
		context.strokeStyle = "pink";
		context.stroke();
	}
}

Color Scheme
Curve border – strokeStyle : red
Curve Fill – fillStyle : yellow
Control Point Path : pink

Leave a Reply

Your email address will not be published. Required fields are marked *