HTML5 Game - Drawing cubic bezier curves and its control points

Description

Drawing cubic bezier curves and its control points

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html>
  <head>
    <title>Bezier Curves</title>

    <style>
      body {//  w  w  w  .j a v  a 2  s.  co m
         background: #eeeeee;
      }

      #canvas {
         background: #ffffff;
         cursor: pointer;
         margin-left: 10px;
         margin-top: 10px;
         -webkit-box-shadow: 4px 4px 8px rgba(0,0,0,0.5);
         -moz-box-shadow: 4px 4px 8px rgba(0,0,0,0.5);
         box-shadow: 4px 4px 8px rgba(0,0,0,0.5);
      }
    </style>
  </head>

   <body>
      <canvas id='canvas' width='600' height='400'>
         Canvas not supported
      </canvas>

    <script>
      let canvas = document.getElementById('canvas'),
    context = canvas.getContext('2d'),
    endPoints = [
       { x: 130, y: 70 },
       { x: 430, y: 270 },
    ],
    controlPoints = [
       { x: 130, y: 250 },
       { x: 450, y: 70 },
    ];

function drawGrid(color, stepx, stepy) {
   context.save()

   context.strokeStyle = color;
   context.fillStyle = '#ffffff';
   context.lineWidth = 0.5;
   context.fillRect(0, 0, context.canvas.width, context.canvas.height);

   for (let i = stepx + 0.5; i < context.canvas.width; i += stepx) {
     context.beginPath();
     context.moveTo(i, 0);
     context.lineTo(i, context.canvas.height);
     context.stroke();
   }

   for (let i = stepy + 0.5; i < context.canvas.height; i += stepy) {
     context.beginPath();
     context.moveTo(0, i);
     context.lineTo(context.canvas.width, i);
     context.stroke();
   }

   context.restore();
}

function drawBezierCurve() {
   context.strokeStyle = 'blue';
   context.fillStyle = 'yellow';

   context.beginPath();
   context.moveTo(endPoints[0].x, endPoints[0].y);
   context.bezierCurveTo(controlPoints[0].x, controlPoints[0].y,
                         controlPoints[1].x, controlPoints[1].y,
                         endPoints[1].x, endPoints[1].y);
   context.stroke();
}

function drawEndPoints() {
   context.strokeStyle = 'blue';
   context.fillStyle = 'red';

   endPoints.forEach( function (point) {
      context.beginPath();
      context.arc(point.x, point.y, 5, 0, Math.PI*2, false);
      context.stroke();
      context.fill();
   });
}

function drawControlPoints() {
   context.strokeStyle = 'yellow';
   context.fillStyle = 'blue';

   controlPoints.forEach( function (point) {
      context.beginPath();
      context.arc(point.x, point.y, 5, 0, Math.PI*2, false);
      context.stroke();
      context.fill();
   });
}

drawGrid('lightgray', 10, 10);

drawControlPoints();
drawEndPoints();
drawBezierCurve();

      </script>
  </body>
</html>

Related Topic