流畅的JavaScript动画

时间:2009-08-24 12:54:15

标签: javascript animation

以下是一些代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<style>
body { margin:0; padding:0; }
#a {
    position:absolute;
    background:#0FF;
    left:0;
    height:300px;
    width:120px;
}
input, #a {
    margin:10px;
}
</style>
<script>
function foo() {
    box = document.getElementById('a');
    var computedStyle = box.currentStyle || window.getComputedStyle(box, null);
    box.style.left = parseInt(computedStyle.left) + 10 + 'px';
    setTimeout("foo()",20);
}
</script>
</head>

<body>
<input type="button" value="RUN, FORREST, RUN!" onClick="setTimeout('foo()',20)">
<div id="a"></div>
</body>
</html>

正如你所看到的,它在页面上动画DIV,但动画不清晰和平滑 - DIV的边框实际上变形了。 有人知道我怎么能让它正常工作吗?

4 个答案:

答案 0 :(得分:8)

Ditto JustLoren:它在我的机器上工作正常。我不确定你的边界“变形”是什么意思......也许你在谈论tearing?如果是这样,我担心你无能为力。

传统的撕裂解决方案是等待vsync绘制你的下一帧,但这种能力在JavaScript中不可用。没有框架可以解决它。 (框架粉丝:请停止建议“使用my_favourite_framework!它解决所有问题!”到您不理解的JavaScript问题。)

正如mck89所暗示的那样,你可以通过绘制更多的帧来使动画更平滑(这也可以减少撕裂的影响),但代价是需要更多的CPU能力来执行。您可能还希望保留一个变量来存储x值,而不是每次都从currentStyle中解析它。浏览器会更简单,更广泛地支持它。

ETA评论:JS中没有具体的最小超时(我有时可以将其降低到1毫秒),但是你可以从动画中获得多少fps高度依赖于浏览器和机器的功能,这就是为什么通常最好将位置/帧基于自动画开始以来经过的时间量(使用新的Date()。getTime())而不是每帧移动/更改固定量。 / p>

在任何情况下,实际上最快的是使用16ms的间隔,相当于60Hz显示器上的一帧(通常的平板默认值)。

答案 1 :(得分:0)

您应该将左坐标增加1 px并为该间隔设置较低的时间。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<style>
body { margin:0; padding:0; }
#a {
    position:absolute;
    background:#0FF;
    left:0;
    height:300px;
    width:120px;
}
input, #a {
    margin:10px;
}
</style>
<script>
function foo() {
    box = document.getElementById('a');
    var computedStyle = box.currentStyle || window.getComputedStyle(box, null);
    box.style.left = parseInt(computedStyle.left) + 1 + 'px';
    setTimeout("foo()",1);
}
</script>
</head>

<body>
<input type="button" value="RUN, FORREST, RUN!" onClick="setTimeout('foo()',20)">
<div id="a"></div>
</body>
</html>

答案 2 :(得分:-4)

JQuery和YUI以及几乎所有其他js库都提供动画实用程序,也许你应该研究一下。

答案 3 :(得分:-4)

根据我的经验,mootools(http://mootools.net)提供最流畅的动画。

相关问题