CanvasでquadraticCurveToしてみる。

正多角形の表示とその頂点nと頂点n+1をつないでできる2次ベジェ曲線を書く。

紫の線が多角形。

緑が2次ベジェ曲線

赤が図形中心とベジェ曲線の制御点を結ぶ線分。

以下、ソース。

var ceil = Math.ceil;
var round = Math.round;
var cos = Math.cos;
var sin = Math.sin;
var tan = Math.tan;
var pow = Math.pow;
var sqrt = Math.sqrt;
var pi = Math.PI;
var pi_3 = Math.PI/3;

function initialize(){
  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');
  ctx.fillRect(0,0,500,300);
  var drawline = function(p1,p2,color){
    ctx.beginPath();
    ctx.strokeStyle = color || 'red';
    ctx.moveTo(p1[0],p1[1]);
    ctx.lineTo(p2[0],p2[1]);
    ctx.moveTo(p1[0],p1[1]);
    ctx.closePath();
    ctx.stroke();
  };
  var drawcurve = function(p1,cp,p2,color){
    ctx.beginPath();
    ctx.strokeStyle = color;
    ctx.moveTo(p1[0],p1[1]);
    ctx.quadraticCurveTo(cp[0],cp[1],p2[0],p2[1]);
    ctx.moveTo(p1[0],p1[1]);
    ctx.closePath();
    ctx.stroke();
  };
  
  var regularpolygon = function(center,radius,vertexCount,color){
    var t0 = 2 * pi/vertexCount;
    var t = 0;
    var firstvertex = lastvertex = [radius + center[0],center[1]];
    for(var i=0,t=0;i<vertexCount;i++,t+=t0){
      vertex = [radius * cos(t) + center[0],radius * -sin(t) + center[1]];
      drawline(lastvertex,vertex,color);
      lastvertex = vertex;
    }
    drawline(lastvertex,firstvertex,color);
  };
  var polygonwithcurve = function(center,radius,vertexcount,color){
    var t0 = 2 * pi/vertexcount;
    var t = 0;
    var firstvertex = lastvertex = [radius + center[0],center[1]];
    var cp_radius = sqrt(pow(radius,2) + pow(radius * -tan(t0/2),2));
    for(var i=0,t=t0;i<vertexcount;i++,t+=t0){
      var vertex = [radius * cos(t) + center[0],radius * -sin(t) + center[1]];
      drawline(lastvertex,vertex,color);
      drawline(lastvertex,vertex,color);
      var ctrlpoint = [cp_radius * cos(t-t0/2) + center[0],cp_radius * -sin(t-t0/2) + center[1]];
//        drawline(center,ctrlpoint,'red');
      drawcurve(lastvertex,ctrlpoint,vertex,'rgba(0,255,255,0.7)');
      lastvertex = vertex;
    }
  };

  var center = [100,100];
  //      regularpolygon(center,100,3,'blue');
  var row = 2;
  var col = 4
  var radius = 40
  for(var j=0;j<row;j++){
    for(var i=0;i<col;i++){
      polygonwithcurve([center[0] + i * 100,center[1] + j * 100],radius,i + 3 + col * j,'rgba(255,0,255,0.7)');
    }
  }
}
window.addEventListener('load',initialize,false);