2

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?

3

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.