Cubic Bezier Curves

In this chapter you will learn:

  1. How to draw Cubic Bezier Curves

Drawing Cubic Bezier Curves

<!DOCTYPE HTML><!--from j  a v  a2s .co  m-->
<html>
<head>
<style>
canvas {
      border: thin solid black
}

body>* {
      float: left;
}
</style>
</head>
<body>
      <canvas id="canvas" width="500" height="840"> 
      Your browser doesn't support the <code>canvas</code> element 
      </canvas>
      <script>
            var canvasElem = document.getElementById("canvas");
            var ctx = canvasElem.getContext("2d");
            var startPoint = [ 20, 100 ];
            var endPoint = [ 200, 100 ];
            var cp1 = [ 20, 50 ];
            var cp2 = [ 30, 50 ];
            function draw() {
                  ctx.lineWidth = 3;
                  ctx.strokeStyle = "black";
                  ctx.beginPath();
                  ctx.moveTo(startPoint[0], startPoint[1]);
                  ctx.bezierCurveTo(cp1[0], cp1[1], cp2[0], cp2[1], endPoint[0],endPoint[1]);
                  ctx.stroke();
                  ctx.lineWidth = 1;
                  ctx.strokeStyle = "red";
                  var points = [ startPoint, endPoint, cp1, cp2 ];
                  for ( var i = 0; i < points.length; i++) {
                        drawPoint(points[i]);
                  }
                  drawLine(startPoint, cp1);
                  drawLine(endPoint, cp2);
            }
            function drawPoint(point) {
                  ctx.beginPath();
                  ctx.strokeRect(point[0] - 2, point[1] - 2, 4, 4);
            }
            function drawLine(from, to) {
                  ctx.beginPath();
                  ctx.moveTo(from[0], from[1]);
                  ctx.lineTo(to[0], to[1]);
                  ctx.stroke();
            }
            draw();
      </script>
</body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. Creating a Clipping Region
Home » Javascript Tutorial » Canvas
Canvas tag
Canvas Context
Rectangle
Rectangle clear
Drawing State
Drawing state restore
Line width
Line Join Style
Line cap settings
Gradients
Linear Gradient
Radial Gradient
Path
Arcs
Two types of curve
Quadratic Bezier Curves
Cubic Bezier Curves
Clip
Text
Shadow
Transparency
Stoke style