Search code examples
javascriptcreatejstween.js

How can I use tweenJS make bitmap move to some points


I meet the question is like this:

I want make the bitmap move to some points, which be stored in an array. How can I use the tweenJS to get this?

I try the first method is this:

var points = [{x:0, y:0}, {x:100, y:100},{x:200, y:200}];
//The points come from the other method, and data like the points.

for( var i=0; i < points.length; i++ ) {
    createjs.Tween.get( target )
      .to( { x: points[i].x, y: points[i].y }, 600, createjs.Ease.easeIn);            
}

Running the code, my target only move to the first point.So I give up.

Then I try the second method :

var str = 'createjs.Tween.get( target )';
for( var i=0; i < points.length; i++ ) {            
    str += '.to( { x: points[' + i + '].x, y: points[' + i + '].y }, 600, createjs.Ease.easeIn)'            
}

eval( str );

It works perfect, but I worry about the "eval" , not so safe. Can you give me some tips ? Big hug.


Solution

  • Just get the tween once, and then add each to in a loop. Your sample creates multiple tweens which run concurrently:

    var points = [{x:0, y:0}, {x:100, y:100},{x:200, y:200}];    
    var tween = createjs.Tween.get( target ); // Once, outside the loop
    for( var i=0; i < points.length; i++ ) {
          // Add each to() call to the current tween (chains them)
          tween.to( { x: points[i].x, y: points[i].y }, 600, createjs.Ease.easeIn);
    }
    

    That should do it.