如何JS动画工作? [英] How do js animations work?

查看:218
本文介绍了如何JS动画工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着去了解如何使一个JavaScript动画流畅运行,我一直在这里读了一些答案,我发现了一些我不明白。

Im trying to understand how to make a javascript animation run smoothly and I've been reading some answers around here and I found something I don't understand.

下面是链接到的问题平滑JavaScript动画

在大多数选票它说:这就是为什么通常这是一个好主意,基本位置上,因为动画开始以来经过的时间量/帧的答案(使用新的Date()。的getTime())而不是移动/改变一个固定的量每一帧。

In the answer with most votes it says "which is why generally it's a good idea to base position/frame on the amount of time that has elapsed since the start of the animation (using new Date().getTime()) rather than moving/changing a fixed amount each frame."

谁能告诉我,使用方法,从这个回答一个非常非常简单的例子,并解释你再怎么控制动画的速度?

Can anyone show me a very very simple example that uses the method from this answer, and explain how you then control the speed of the animation?

推荐答案

其基本思想是:


  • 您想从0,0在1秒内移动DIV至100.0。

  • 您希望它拥有每秒50帧(使用的setTimeout(乐趣,20))
  • 然而,由于回调不能保证准确地在20ms的运行,你的回调需要弄清楚当它实际运行。例如,假设你的动画开始在时间X,但你的第一个动画回调不叫,直到X + 5ms的。你需要计算的立场,即格应该是在动画为25ms,动画回调不能承担50甚至步骤。

下面是一个非常简单code样品。我通常不code。与全局,但这是显示技术的最简单方法。

Here's a very simple code sample. I don't usually code with globals but this is the easiest way to show the technique.

http://jsfiddle.net/MWWm6/2/

var duration = 1000; // in ms
var startTime; // in ms
var startX = 0;
var endX = 500;
// 0 means try to get as many frames as possible
// > 1: Remember that this is not guaranteed to run as often as requested
var refreshInterval = 0;
var div = document.getElementById('anim');

function updatePosition() {
    var now = (new Date()).getTime();
    var msSinceStart = now - startTime;
    var percentageOfProgress = msSinceStart / duration;
    var newX = (endX - startX) * percentageOfProgress;
    div.style.left = Math.min(newX, endX) + "px";
    if (window.console) {
        console.log('Animation Frame - percentageOfProgress: ' + percentageOfProgress + ' newX = ' + newX);
    }
    if (newX < endX) {
        scheduleRepaint();
    }
}

function scheduleRepaint() {
    setTimeout(updatePosition, refreshInterval);
}

div.onclick = function() {
    startTime = (new Date()).getTime();
    scheduleRepaint();
}

这篇关于如何JS动画工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆