1

我正在通过 JavaScript / jQuery 缩放和移动文本。我不能使用 jQuerys animate() 因为它必须淡入和淡出,并且必须重复并使用更多元素(最终结果:从背景“飞”,向不同方向移动并淡出)。

我的问题:它运行不顺畅并导致相当多的 cpu 使用。这是一个精简版:

<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script type="text/javascript">

    var steps = 300; // steps from start to finish

    // the final css values
    var endValueTop = 300;
    var endValueLeft = 300;
    var endValueFontSize = 100;

    // the current css values (get encreased in doAnimation())
    var currentValueTop = 100;
    var currentValueLeft = 100;
    var currentValueFontSize = 0;

    // the added values in each step
    var stepsTop = (endValueTop - currentValueTop) / steps;
    var stepsLeft = (endValueLeft - currentValueLeft) / steps;
    var stepsFontSize = (endValueFontSize - currentValueFontSize) / steps;

    function doAnimation() {

        // increase current values
        currentValueTop += stepsTop;
        currentValueLeft += stepsLeft;
        currentValueFontSize += stepsFontSize;

        // apply them
        $("#hello").css({
            top: currentValueTop,
            left: currentValueLeft,
            fontSize: currentValueFontSize
        });

        // restart if there are steps left
        if (steps--) {
            window.setTimeout(function(){
                doAnimation();
            }, 50);

        }

    }

    // start the first time
    doAnimation();

</script>

<style>
  article, aside, figure, footer, header, hgroup,
  menu, nav, section { display: block; }
  body { position: relative; }
  p#hello { position: absolute; top: 100px; left: 100px; font-size: 0px; }
</style>
</head>
<body>
  <p id="hello">Hello World</p>
</body>
</html>

在JS BIN上运行示例。

有什么建议么?奖励:如何减少 CPU 负载?非常感谢!

史蒂芬

4

3 回答 3

2

首先,绝对不要在 50 毫秒计时器内使用 jQuery。如果有任何原因导致 CPU 使用率过高,那就是这样。改用这样的东西

var hello = $('#hello')[0].style;

function doAnimation() {

  //code...

  hello.top = curentValueTop + 'px';
  hello.left = currentValueLeft + 'px';
  hello.fontSize = currentValueFontSize + 'px';

  //rest of code...

}

然而,大多数浏览器不能很好地处理字体的平滑和一致的缩放。由于 99% 的情况下网页上的文字不会飞到您的脸上,因此我们不会注意到这一点。以您需要的最大字体大小呈现的文本图像可能会让您更幸运。

此外,50ms ~= 20fps 对于遍历一半屏幕的动画来说并不是特别平滑的帧速率。如果不使用 jQuery 会显着降低 CPU 使用率,您可以尝试更小的间隔。当然,大多数浏览器也不擅长处理高帧率动画。

是的,现代网络浏览器正在努力以四分之一的帧速率完成 20 年前的视频游戏机无法解决的问题。

编辑试试这个http://jsbin.com/oxode/4/edit

我使用该em单位,fontSize因为它接受小数,并使用 15 毫秒计时器(如果浏览器可以跟上,大约 60 fps)。如您所见,它的缩放更平滑,尽管您必须稍微调整动画设置...

于 2010-08-15T19:16:24.460 回答
0

几年前我在手机上非常成功地使用了这个库,也许它的开销很小,足以让它对你来说足够快:

http://dev.opera.com/libraries/animation/

于 2010-08-15T19:06:13.560 回答
0

jQuery 并不是真正为长动画设计的(这就是为什么“慢”小于 1 秒),所以高 CPU 负载并不会真正消失。

您可以做的一件事是使用动画功能 http://api.jquery.com/animate/

这已经做了很多你在那里编程的事情。

于 2010-08-15T19:09:12.503 回答