【问题标题】:css linear-gradient background CPU high usagecss线性渐变背景CPU高使用率
【发布时间】:2021-08-18 08:27:24
【问题描述】:

需要在body中创建线性渐变动画,但是它使用cpu很多,导致风扇大声奔跑。

我找到了这个解决方案 animated linear gradient devouring CPU usage

这个技巧将 cpu 使用率降低到 3-5%,这很棒。但是,当您调整窗口大小时,它会在后台创建一个错误。

尝试创建调整大小功能,因为我猜当您调整窗口大小时,宽度属性会发生变化,从而导致错误。但没有成功。

[Codepen](https://codepen.io/iclassici/pen/poPXRyp)

【问题讨论】:

    标签: css background css-animations cpu-usage


    【解决方案1】:

    在做:

      body.classList.remove('bg');
      body.classList.add('bg');
    

    实际上什么都没有发生,因为在系统有机会重新计算/重绘内容之前就恢复了类。

    您需要像以前一样删除该类,然后等待再恢复它。试试 setTimeout 或 requestAnimationFrame。

    如果您可以将您的代码编写成我们可以在您的问题中运行的 sn-p,这将有助于我们测试并给出更完整的答案。

    更新:使用 codepen 中给出的代码,这个 sn-p 对 resize 函数进行了更改,删除了一个 bganimation 类,设置了一个短的超时并恢复了该类。这确保系统将重置它提供给 GPU 的任何参数。

    注意:在我相当强大的笔记本电脑 Windows 10 上,背景动画主要占用不到 2% 的 CPU 和大约 20% 的 GPU。

    window.addEventListener("resize", myFunction);
    
    function myFunction() {
      body = document.getElementsByTagName('body')[0];
      body.classList.remove('bganimation');
      setTimeout(function() {
        body.classList.add('bganimation');
      }, 100);
    }
    .bg {
      width: 100vw;
      height: 100vh;
    }
    
    .bg::before {
      content: '';
      position: fixed;
      z-index: -2;
      top: 0;
      left: 0;
      width: 600%;
      height: 100%;
      bottom: 0;
      background: linear-gradient(45deg, #F17C58, #E94584, #24AADB, #27DBB1, #FFDC18, #FF3706);
      background-size: 100% 100vh;
      background-repeat: no-repeat no-repeat;
      background-position: left top;
    }
    
    .bganimation {
      animation: gradient 16s linear infinite alternate;
    }
    
    @keyframes gradient {
      0% {
        transform: translateX(0);
      }
      100% {
        transform: translateX(-400vw);
        /* 5/6x100% */
      }
    }
    <body class="bg bganimation">
    </body>

    【讨论】:

    • 非常感谢您抽出宝贵时间。这是一个代码笔codepen.io/iclassici/pen/poPXRyp
    • 我在运行 codepen 时看到右侧出现黑色区域​​ - 我想在一个动画周期结束时 - 这是故意的吗?
    • 我已经根据你的 codepen 添加了一个 sn-p。我似乎必须调整背景图像的大小才能在最后看到白色。
    • 非常感谢!我能够根据我的需要调整您的代码。再次感谢您!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 2021-05-25
    相关资源
    最近更新 更多