使用 JavaScript 平滑缩放和移动文本

发布于 2024-09-14 03:01:34 字数 2198 浏览 4 评论 0 原文

我正在通过 JavaScript / jQuery 缩放和移动文本。我不能使用 jQuery 的 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负载?多谢!

史蒂芬

I'm having a text scaled and moved via JavaScript / jQuery. I can't use jQuerys animate() because it has to fade in and out and has to be repeated and with more elements (end result: "flying" from the background, moving in different directions and fading out).

My problem: It's not running smoothly and causes quite the cpu-usage. Here's a stripped down version:

<!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>

Running example on JS BIN.

Any suggestions? Bonus: How to reduce the cpu load? Thanks a lot!

Steffen

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

回忆躺在深渊里 2024-09-21 03:01:34

首先,绝对不要在 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< /a>

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

Well first off, absolutely do not use jQuery within a 50ms timer. If anything is causing high CPU usage it is that. Use something like this instead

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

function doAnimation() {

  //code...

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

  //rest of code...

}

However, smoothly and consistently scaling of fonts is something most browsers do not handle well. Since 99% of the time the text on a web page is not flying into your face, we do not notice this. You might have more luck with an image of the text rendered at the maximum font size you need.

Also, 50ms ~= 20fps which is not a particularly smooth frame rate for animations that traverse half of the screen. If not using jQuery significantly reduces CPU usage you could try a smaller interval. Of course most browsers are not good at handling high frame rate animations either.

Yup, modern web browsers, struggling to do things that 20 year old video game consoles had no problem with, at a quarter of the frame rate.

EDIT Try this http://jsbin.com/oxode/4/edit

I used the em unit for fontSize as it accepts fractional numbers, and used a 15ms timer (about 60fps if the browser can keep up). As you can see it scales smoother, although you will have to adjust your animation settings a bit...

南城旧梦 2024-09-21 03:01:34

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

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

I've used this library some years ago quite successfully on cellphones, maybe it has little enough overhead to make it fast enough for you:

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

痴骨ら 2024-09-21 03:01:34

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

您可以做的一件事是使用 animate 函数
http://api.jquery.com/animate/

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

jQuery wasn't really designed for long animations (that's why "slow" is less than 1 second) so high CPU load isn't really going to go away.

One thing you could do is to use the animate function
http://api.jquery.com/animate/

That already does a lot of what you had programmed there.

不气馁 2024-09-21 03:01:34
<!DOCTYPE html><html><body>

<style>
#txt{position:absolute; left:0px;}
</style>

<div id="txt">Salam</div>   <br><br>
<button onclick="setTimeout(fn, 200)">GO ON</button>

<script>
function fn() {document.getElementById("txt").style.left="200px";
               document.getElementById("txt").style.transition="2s";
              }
</script></body></html>

原生 JS 和 CSS 可以处理这个问题。
在 CSS 中,设置默认文本位置。
在 JavaScript 中,有 2 个步骤:
1 = 设置新位置。
2 = 将“过渡”值添加到您的样式属性中。

<!DOCTYPE html><html><body>

<style>
#txt{position:absolute; left:0px;}
</style>

<div id="txt">Salam</div>   <br><br>
<button onclick="setTimeout(fn, 200)">GO ON</button>

<script>
function fn() {document.getElementById("txt").style.left="200px";
               document.getElementById("txt").style.transition="2s";
              }
</script></body></html>

Native JS and CSS can handle this.
In the CSS, set your default text position.
In JavaScript, 2 steps:
1 = Set the new position.
2 = Add "transition" value to you style attibute.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文