【问题标题】:CSS, "-webkit-animation" consumes too much CPU on Google ChromeCSS,“-webkit-animation”在 Google Chrome 上消耗过多 CPU
【发布时间】:2015-11-27 08:03:46
【问题描述】:

我使用以下 CSS:

.navbar .agesbar {
        height: 55px;
        background-image: url('/img/nicebar.jpg');
        background-repeat: repeat-y;
        background-position: center center;
        background-size: cover;

        width: 100%;
        -webkit-animation: agesTicker 120s linear infinite;
        animation: agesTicker 120s linear infinite;
    }

    @-webkit-keyframes agesTicker {
        from {background-position: 0 0;}
        to {background-position: -2446px 0;}
    }       
    @keyframes agesTicker {
        from {background-position: 0 0;}
        to {background-position: -2446px 0;}
    }

一切正常,不幸的是,它在谷歌浏览器上消耗了太多的 CPU。 (10-20%)。在 Firefox 甚至 Internet Explorer 上,它不会浪费那么多 CPU(仅 2-3%)。 我通过添加以下内容修复了高 CPU 使用率:

will-change: transform;

强制 gpu 加速,不幸的是它并不能解决性能问题,因为现在 GPU “工作更重”:笔记本电脑越来越热,我笔记本电脑的风扇声音越来越大。

我有两个问题:1. 为什么这个动画在 Chrome 上效果这么差,而在其他浏览器上却很好? 2. 这个动画有什么替代品吗,比如jquery脚本?

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    您可以尝试使用 CSS transition 而不仅仅是使用 js/jQuery 更改背景位置:

    $(document).ready(function() {
      $('.test').css({'background-position': '0px -200px'});
    });
    .test {
      background: url('http://lorempixel.com/400/200/sports/') no-repeat 0 0;
      width: 100px;
      height: 100px;
      transition: background-position 2s;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="test"></div>

    【讨论】:

    • 感谢您的代码。不幸的是,它也运行缓慢。 CPU 使用率甚至更高(一直为 20%),在 Firefox 上也高达 10% :(
    • @Przmus 我希望你关闭旧代码。你也试过其他电脑吗?因为我看不出问题。此测试是否还会增加 CPU 使用率?
    • 你是对的。这很奇怪,但是这段代码在这里可以正常工作(使用正常的 -webkit-animation):jsfiddle.net/z6b5cvxm 我不知道为什么它在我的网站上有如此高的 CPU 使用率,而且只有 Chrome...
    【解决方案2】:

    我猜这个问题是由于background-size: cover,据我记得调整大小的图像没有缓存,所以浏览器每次都必须重新计算

    尝试删除它,看看有什么变化

    【讨论】:

      【解决方案3】:

      我猜background-position 动画很慢。也许translate的动画会更快?

      【讨论】:

        猜你喜欢
        • 2016-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-04
        • 2016-07-18
        • 1970-01-01
        • 2023-03-18
        • 1970-01-01
        相关资源
        最近更新 更多