Creating a simple animation

Now, it's time to create our simplest animation with TweenJS. It is a simple but powerful API, which gives you the ability to develop animations with method chaining.

Scenario

The animation has a red ball that comes from the top of the Canvas element and then drops down.

Scenario

In the preceding screenshot, you can see all the steps of our simple animation; consequently, you can predict what we need to do to prepare this animation. In our animation, we are going to use two methods: get and to.

The following is the complete source code for our animation:

var canvas = document.getElementById("canvas");
var stage = new createjs.Stage(canvas);

var ball = new createjs.Shape();
ball.graphics.beginFill("#FF0000").drawCircle(0, 0, 50);

ball.x = 200;
ball.y = -50;

var tween = createjs.Tween.get(ball) to({
  y: 300
}, 1500, createjs.Ease.bounceOut);

stage.addChild(ball);
createjs.Ticker.addEventListener("tick", stage);

In the second and third line of the JavaScript code snippet, two variables are declared, namely; the canvas and stage objects. In the next line, the ball variable is declared, which contains our shape object. In the following line, we drew a red circle with the drawCircle method (we have discussed about the drawCircle method in the previous chapter). Then, in order to set the coordinates of our shape object outside the viewport, we set the x axis to -50 px.

After this, we created a tween variable, which holds the Tween object; then, using the TweenJS method chaining, the to method is called with duration of 1500 ms and the y property set to 300 px. The third parameter of the to method represents the ease function of tween, which we set to bounceOut in this example.

In the following lines, the ball variable is added to Stage and the tick event is added to the Ticker class to keep Stage updated while the animation is playing. You can also find the Canvas element in line 30, using which all animations and shapes are rendered in this element.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.208.12