HTML5 Game - Create a closed curve

Introduction

The following code computes an initial midpoint.

The initial midpoint is an average of the first and last points.

After moving to the initial midpoint it loops through all the rest, figuring midpoints for each one.

It finally draws its last curve back to the initial midpoint.

Demo

ResultView the demo in separate window

<!doctype html>  
<html>  
 <head>  
  <meta charset="utf-8">  
  <title>Multi Curve 3</title>  
  <style>canvas{border:1px solid red;}</style>  
 </head>  //from   w ww.  j a v a  2  s .  c o m
 <body>  
  <canvas id="canvas" width="400" height="400"></canvas>  
  <script>  
  window.onload = function () {  
    let canvas = document.getElementById('canvas'),  
        context = canvas.getContext('2d'),  
        points = [],  
        numPoints = 9,  
        ctrlPoint = {},  
        ctrlPoint1 = {};  
     
    for (let i = 0; i < numPoints; i++) {  
      points.push({  
        x: Math.random() * canvas.width,  
        y: Math.random() * canvas.height  
      });  
    }  
     
    //find the first midpoint and move to it  
    ctrlPoint1.x = (points[0].x + points[numPoints-1].x) / 2;  
    ctrlPoint1.y = (points[0].y + points[numPoints-1].y) / 2;  
    context.beginPath();  
    context.moveTo(ctrlPoint1.x, ctrlPoint1.y);  
     
    //curve through the rest, stopping at each midpoint  
    for (i = 0; i < numPoints - 1; i++) {  
      ctrlPoint.x = (points[i].x + points[i+1].x) / 2;  
      ctrlPoint.y = (points[i].y + points[i+1].y) / 2;  
      context.quadraticCurveTo(points[i].x, points[i].y, ctrlPoint.x, ctrlPoint.y);  
    }  
     
    //curve through the last point, back to the first midpoint  
    context.quadraticCurveTo(points[i].x, points[i].y, ctrlPoint1.x, ctrlPoint1.y);  
    context.stroke();  
  };  
  </script>  
 </body>  
</html>

Related Topic