Search code examples
javascriptanimationcanvaskineticjscurve

How to animate object on curve path in Kineticjs


I would like to create a path as some curve, probably quad curve. It can be done similarly to http://www.html5canvastutorials.com/labs/html5-canvas-modify-curves-with-anchor-points-using-kineticjs/

Then I am able to create image object. However, I want to animate it along the created path (move it from start point to end point of the curve). I can use Javascript+Canvas+KineticJS(v 4.7.1). Is there any way, how to do it? I can't find any example which solves this.


Solution

  • Demo: http://jsfiddle.net/m1erickson/nnU89/

    enter image description here

    You can calculate points along a quadratic curve with this formula:

    // Calc an XY along a quadratic curve at interval T
    // T==0.00 at start of curve, T==1.00 at end of 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} );
    }
    

    You pass in:

    • the curve points (startPt, controlPt, endingPt)
    • the interval along the curve at which to calculate XY (T)
    • Note: T==0 at the start of the curve and T==1.00 at the end of the curve

    Then you can create a Kinetic.Animation that animates along the curve:

    var animation = new Kinetic.Animation(function(frame) {
    
        // calc an XY along the curve at interval T
    
        var pos=getQuadraticBezierXYatT(qStart,qControl,qEnd,T/100);
    
        // set some Kinetic object to that position
    
        yourObject.setPosition(pos);    
    
        // change T for the next animation frame
    
        T+=TDirection;
        if(T<0 || T>100){ TDirection*=-1; T+=TDirection}
    
    }, layer);