How to draw a Bezier Curve with HTML5 Canvas?

HTMLWeb DevelopmentFront End Technology

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 Bezier curve with HTML5 canvas, use the bezierCurveTo() method. The method adds the given point to the current path, connected to the previous one by a cubic Bezier curve with the given control points.

Bezier Curve

You can try to run the following code to learn how to draw a Bezier curve on HTML5 Canvas. The x and y parameters in bezierCurveTo() method are the coordinates of the endpoint. cp1x and cp1y are the coordinates of the first control point, and cp2x and cp2y are the coordinates of the second control point.

Example

Live Demo
<!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');
         ctx.beginPath();
         ctx.moveTo(75,40);
         ctx.bezierCurveTo(75,37,70,25,50,25);
         ctx.bezierCurveTo(20,25,20,62.5,20,62.5);
         ctx.bezierCurveTo(20,80,40,102,75,120);
         ctx.bezierCurveTo(110,102,130,80,130,62.5);
         ctx.bezierCurveTo(130,62.5,130,25,100,25);
         ctx.bezierCurveTo(85,25,75,37,75,40);
         ctx.fill();
      </script>
      
   </body>
</html>
raja
Published on 07-Feb-2018 08:59:34
Advertisements