Skip to content

5. Animation

CookieShade edited this page Jul 25, 2016 · 4 revisions

The animation system

When displaying an animation, it is necessary to render multiple frames in quick succession. BETA.js provides a simple API for this purpose.

BETA.animate(animationFn)

Calls a function every time the screen updates. The frame rate depends on the refresh rate of the monitor used.
Throws an error if there is already an animation running.

The animationFn is called with one argument, which is the time since the last frame of the animation, in seconds. This measure, called delta time, is used to keep the speed of an animation independent of the frame rate, by multiplying the speed of an object with the delta time. See this post for a more detailed explaination of delta time.

var renderer = BETA.getRenderer("myCanvas");

var position = {x: 50, y: 50};
var speed = {x: 20, y: 10};

BETA.animate(function (deltaTime)
{
    position.x += speed.x * deltaTime;
    position.y += speed.y * deltaTime;

    renderer.clear();
    renderer.fillCircle(position, 50, "lightblue");
});

BETA.stopAnimation(id)

Stops the current animation from rendering any more frames. Throws an error if no animation is running.

var renderer = BETA.getRenderer("myCanvas");

var timeElapsed = 0;

var position = {x: 50, y: 50};
var speed = {x: 20, y: 10};

BETA.animate(function (deltaTime)
{
    timeElapsed += deltaTime;

    position.x += speed.x * deltaTime;
    position.y += speed.y * deltaTime;

    renderer.clear();
    renderer.fillCircle(position, 50, "lightblue");

    if (timeElapsed > 5)
    {
        BETA.stopAnimation();
    }
});
Clone this wiki locally