Zaaier
Zaaier

Reputation: 746

Animating a simple 2D line in vanilla JS

I've been reading through guides on the internet, but I haven't been able to find a way to animate a line from one position to a new position.

Apparently this requires "tweening", to create a smooth animation, and isn't built in? And all I ever find is "Check out THIS JavaScript framework that handles that for you!"

Does something exist in vanilla JavaScript (or jQuery) akin to:

animateLine(current, target, duration, easingFunction)
{
    move(line.x1, target.x1, duration, easingFunction);
    move(line.y1, target.y1, duration, easingFunction);
    move(line.x2, target.x2, duration, easingFunction);
    move(line.y2, target.y2, duration, easingFunction);
}

I want to just iterate through an array of lines, calling animateLine(lines[i], targets[i], duration, easingFunction) inside of setInterval().

Upvotes: 1

Views: 791

Answers (1)

inorganik
inorganik

Reputation: 25535

Lots of different ways to skin this cat... However, as far as the frame-by-frame animation, you want requestAnimationFrame. This function calls whatever you pass to it, and passes a timestamp. Then it's just a matter of changing properties of these "lines" to move them across the screen.

If you were animating an <hr> element you could make it absolutely positioned and then just change the top amount each frame:

html:

<hr id="myLine"/>

css:

#myLine { position:absolute; width:100% }

js:

function easeOutQuad(t) { return t*(2-t) };
var startTime = null,
    percent, elapsed,
    duration = 3000,
    end = 400,
    hr = document.getElementById('myLine');

function step(timestamp) {
    if (startTime === null) startTime = timestamp;

    elapsed = timestamp - startTime;
    percent = elapsed/duration;

    if (elapsed < duration) {

        // apply easing fn
        percent = easeOutQuad(percent);

        var frameDist = end * percent;
        hr.style.top = frameDist + 'px';
        // next frame
        requestAnimationFrame(step);
    } else {
        // on complete...
    }
}

// begin
requestAnimationFrame(step);

Here is a fiddle: http://jsfiddle.net/oytwdk9s/

If you want to support IE9 and older, you'll need a polyfill for requestAnimationFrame.

Upvotes: 1

Related Questions