To draw a quadratic curve, we use the quadraticCurve() method. However, we need to combine the quadraticCurve() method with the beginPath() and moveTo() methods in order to draw a quadratic curve. The beginPath() and moveTo() methods define the starting point of the quadratic curve. The quadraticCurve() method is to define the lowest point to the end point of the quadratic curve. The syntax of the quadraticCurve() method is
quadraticCurveTo(x1, y1, x2, y2)
*(x1, y1) is the lowest point. *(x2, y2) is the end point.
Before we can draw a quadratic curve, we need to create a canvas by defining its width and height, using the <canvas> tag. Please note that <canvas> is an HTML5 tag that may not be supported by certain versions of browsers. Please refer to our tutorial for further explanation on drawing graphics.
This JavaScript is to draw a quadratic curve with predefined starting point and ending point
<canvas id="myCanvas" style="border: 1px solid #d3d3d3;" width="250" height="300"> </canvas> <input type="button" value="Draw Curve" Onclick="DrawCurve()"> <script> function DrawCurve() { var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.beginPath(); ctx.moveTo(20, 20); ctx.quadraticCurveTo(90, 400, 200, 20); ctx.stroke(); } </script>
Please click on the Draw Curve button to view the output.
The next example let the user input the starting point as well as the lowest point and the ending point. We also add a clearRect method to clear the canvas. The syntax of the clearRect is
ctx.clearRect(0, 0,canvas.width, canvas.height)
* (0,0) is the coordinates of the origin that refer to the upper top-left corner of the canvas. Besides that, we also create a canvas with dark blue background. In addition, we want to draw white line so we add the code ctx.strokeStyle = 'white'.
<canvas id="myCanvas" style="border: 1px solid #d3d3d3;" width="250" height="300"> </canvas> <input type="button" value="Draw Curve" Onclick="DrawCurve()"> <script> function DrawCurve() { var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.beginPath(); ctx.moveTo(a, b); ctx.quadraticCurveTo(x1, y1, x2,y2); ctx.stroke(); } </script>
Let's say the coordinates of the starting point is (a,b), the lowest point of the quadratic graph is (x1,x2) and the end point of the quadratic graph is (x2,y2). Please enter these values in the following text boxes:
a=
b=
x1=
y1=
x2=
y2=
Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy