How to draw a quadratic curve on HTML5 Canvas?


The HTML5 <canvas> tag is used to draw graphics, animations, etc. using scripting. It is a new tag introduced in HTML5. The canvas element has a DOM method called getContext, which obtains rendering context and its drawing functions. This function takes one parameter, the type of context 2d.

To draw a Quadratic curve with HTML5 canvas, use the quadraticCurveTo() method. This method adds the given point to the current path, connected to the previous one by a quadratic Bezier curve with the given control point.

You can try to run the following code to learn how to draw a quadratic curve on HTML5 Canvas. The x and y parameters in quadraticCurveTo() method are the coordinates of the endpoint. cpx and cpy are the coordinates of the control point.

Example

<!DOCTYPE html>
<html>
   <head>
      <title>HTML5 Canvas Tag</title>
   </head>

   <body>
      <canvas id="newCanvas" width="500" height="300" style="border:1px
         solid #000000;"></canvas>
      <script>
         var c = document.getElementById('newCanvas');
         var ctx = c.getContext('2d');

         // Draw shapes
         ctx.beginPath();
         ctx.moveTo(75,25);
         ctx.quadraticCurveTo(25,25,25,62.5);
         ctx.quadraticCurveTo(25,100,50,100);
         ctx.quadraticCurveTo(50,120,30,125);
         ctx.quadraticCurveTo(60,120,65,100);
         ctx.quadraticCurveTo(125,100,125,62.5);
         ctx.quadraticCurveTo(125,25,75,25);
         ctx.stroke();
      </script>
   </body>
</html>

Output

Swarali Sree
Swarali Sree

I love thought experiments.

Updated on: 16-Dec-2021

727 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements