Question

Is there a way to get an x,y value for a normalized 0 to 1 t value out of a KineticJS.Spline class?

For instance, if I'm interested in drawing circles on top of the spline at a constant interval.

If not, is there a good alternative JS library for this?

Was it helpful?

Solution

Sure...

You can get the starting point of the Kinetic.Spline by calling mySpline.getPoints().

You can get the curve definitions for a spline by calling the internal mySpline.getTensionPoints().

  • The first curve definition is a quadratic curve (controlX, controlY, endX, endY)

  • The rest of the curve defs are cubic curves. (control1X, control1Y, control2X, control2Y, endX, endY);

Armed with this info, you can calculate any X/Y at interval T on each curve.

The way you framed your question indicates you already have the 2 formulas to calculate X/Y at interval T for quad and cubic curves.

Here is the equation to plot a quadratic curve at interval T:

///////////////////////////////////////////////////
// plot Quadratic Curve
///////////////////////////////////////////////////
function getQuadraticBezierXYatT(startPt,controlPt,endPt,T) {
    var x = Math.pow(1-T,2) * startPt.x + 2 * (1-T) * T * controlPt.x + Math.pow(T,2) * endPt.x; 
    var y = Math.pow(1-T,2) * startPt.y + 2 * (1-T) * T * controlPt.y + Math.pow(T,2) * endPt.y; 
    return( {x:x,y:y} );
}

Here is the equation to plot a cubic Bezier curve at interval T:

///////////////////////////////////////////////////
// plot Cubic Bezier Curve
///////////////////////////////////////////////////
function getCubicBezierXYatT(startPt,controlPt1,controlPt2,endPt,T){
    var x=CubicN(T,startPt.x,controlPt1.x,controlPt2.x,endPt.x);
    var y=CubicN(T,startPt.y,controlPt1.y,controlPt2.y,endPt.y);
    return({x:x,y:y});
}

// cubic helper formula at T
function CubicN(T, a,b,c,d) {
    var t2 = T * T;
    var t3 = t2 * T;
    return a + (-a * 3 + T * (3 * a - a * T)) * T
    + (3 * b + T * (-6 * b + b * 3 * T)) * T
    + (c * 3 - c * 3 * T) * t2
    + d * t3;
}

If you want to peek at the spline internals, they are in the line.js source file:

https://github.com/ericdrowell/KineticJS/blob/master/src/shapes/Line.js

[ Update: Ouch! -- KineticJS has replaced .getTensionPoints with .allPoints ]

The mySpline.getTensionPoints method has been replace by mySpline.allPoints.

You can get the starting point of the Kinetic.Spline by calling mySpline.getPoints().

You can get the curve definitions for a spline by calling the internal mySpline.allPoints

var curvePoints=mySpline.allPoints;

Now the points are JS point objects in the form {x:,y:}.

  • The first curve definition is a quadratic curve: {x:controlX, y:controlY}, {x:endX, y:endY}

  • The rest of the curve defs are cubic curves: {x:control1X, y:control1Y}, {x:control2X, y:control2Y}, {x:endX, y:endY}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top