How to animate object on curve path in Kineticjs

让人想犯罪 __ 提交于 2019-12-08 10:37:51

问题


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.


回答1:


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

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);


来源:https://stackoverflow.com/questions/22116611/how-to-animate-object-on-curve-path-in-kineticjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!