开发者

JavaScript Curve Generation

How can I write a function that takes an array of 2D points and returns the Bezier/Quadractic curve(s开发者_运维百科) so I can redraw it later using the HTML5 Canvas bezierCurveTo or quadraticCurveTo method?


EDIT: improved.

See a demo which uses the code below.

var makeCurveArgs = function(points) {
  var copy = points.slice();
  var result = [];
  copy.shift(); //drop the first point, it will be handled elsewhere
  var tangent;
  if(copy.length >= 3) {
    var cp1 = copy.shift();
    var cp2 = copy.shift();
    var p2 = copy.shift();

    result.push([cp1[0], cp1[1], cp2[0], cp2[1], p2[0], p2[1]]);            
  }
  while(copy.length >= 2) {
    var cp1 = [2 * p2[0] - cp2[0], 2 * p2[1] - cp2[1]];
    var cp2 = copy.shift();
    var p2 = copy.shift();
    result.push([cp1[0], cp1[1], cp2[0], cp2[1], p2[0], p2[1]]);            
  }
  return result;
}

var notThatHard = function(points) {
  var origin = points[0].slice();
  var curves = makeCurveArgs(points);
  var drawCurves = function(context) {


    context.beginPath();
    context.moveTo(origin[0], origin[1]);
      for(var i = 0; i < curves.length; i++) {
      var c = curves[i];
      context.bezierCurveTo(c[0], c[1], c[2], c[3], c[4], c[5]);
  }
  };
  return drawCurves;
};

The general approach is that you give me the coordinates of your points and control points and I give you back a function which will execute that path on a canvas context.

The function I give requires an array of 2N+2 2-element arrays; each 2-element array is an (x,y) coordinate. The coordinates are used as follows:

points[0]: starting point of the curve
points[1]: lies on a line tangent to the beginning of the 1st bezier curve
points[2]: lies on a line tangent to the end of the 1st bezier curve
points[3]: end of 1st bezier curve, start of 2nd bezier curve
points[4]: lies on a line tangent to the end of the 2nd bezier curve
points[5]: end of 2nd bezier curve, start of 3rd curve
...
points[2*K+2]: lies on a line tangent to the end of the Kth bezier curve
points[2*K+3]: end of Kth bezier curve, start of (K+1)th

I think a similar function for quadraticCurveTo wouldn't be hard to write.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜