Moving elements with javascript

北慕城南 提交于 2019-12-01 08:37:34

Here you can find a good Javascript Animation tutorial: http://www.schillmania.com/content/projects/javascript-animation-1

But what you said is right. Jquery Animate uses setTimeout, moving the object based in calculations of duration, position and easing.

There is a recent function called requestAnimationFrame which runs a function as soon as possible. This is a good practice since it has been made for animation purposes.

The way it works in terms of coding is the same as setTimeout, e.g. when the function finishes you call requestAnimationFrame.

In the function, you fetch the current time to see how the object should be positioned at that time.

You can cancel a pending function it with cancelRequestAnimationFrame, passing the return value of requestAnimationFrame.

Currently this is not cross-browser and the functions are vendor-prefixed, e.g. webkitRequestAnimationFrame for Chrome.

E.g.: http://jsfiddle.net/pimvdb/G2ThU/1/.

var div = document.getElementById('div');
var animation;

function move() {
    var time = Math.round((new Date()).getTime() / 10) % 200;

    div.style.left = time + 'px';

    animation = requestAnimationFrame(move);
}

document.getElementById("start").onclick = function() {
    animation = requestAnimationFrame(move);
}

document.getElementById("stop").onclick = function() {
    cancelRequestAnimationFrame(animation);
}

Intervals are preferable, I believe, because you only set it once in the code rather than once per frame. It only needs to read the code once and reuse it several times, rather than reading it every time it is created.

10ms is a bit short. The computer can natively support intervals of about 16ms, then more precise timers can be used for faster intervals, however these are very power-consuming. IE9 supports both, depending on the computer's power settings, but ideally you shouldn't need anything faster than 50ms (20 FPS).

I like to move a fraction of the total distance, based on the time that has passed since the animation started. This way, no matter what the speed of the computer and browser, the animation will always take the exact same amount of time. Guaranteed.

Something like:

interval = setInterval(function() {
    // do stuff
    if( /*animation ended*/) clearInterval(interval);
},time);

jQuery is easy for some, but personally I find nothing beats writing it yourself in plain, old JS. Much easier to understand what's going on exactly, rather than relying on some framework to get it right for you.

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