CSS keyframe animation CPU usage is high, should it be this way?

前端 未结 5 1023
梦毁少年i
梦毁少年i 2020-12-12 12:34

I use following keyframe animation on several elements:

@keyframes redPulse {
    from { background-color: #bc330d; box-shadow: 0 0 9px #333; }
    50% { bac         


        
5条回答
  •  攒了一身酷
    2020-12-12 12:57

    To a particular case of 'pulsing' background animation, reported here, I've come up with a css+js solution.

    In my case the background animation was on background-position property rather than on the background-color, but the principle is the same.

    Ok, let's say you have a block with a particular background:

    ...

    Let's style it: (scss)

    .nice-block {
      background-color: red;
      //or it can be: background: linear-gradient(45deg, #red, #white, #red);
      //and:          background-size: 600% 600%;
    
      //the transform and will-change properties
      //are here to only enable GPU
      transform: translateZ(0);
      -webkit-transform: translateZ(0);
      -ms-transform: translateZ(0);
      will-change: transform;
    
      transition: background-color 5s ease;
      //if you want to add a pulsing effect 
      //to a gradient, see the following two lines:
      // background-position: 0% 50%!important;
      // transition: background-position 5s ease;
    
      &.animated {
        background-color: white;
        //and in case of gradient animation:
        // background-position: 100% 50%!important;
      }
    }
    

    Now it's time to make the effect happen by adding a class 'animated' to the block with some JavaScript:

    var bgAnimateTimer;
    function animateBg () {
      clearTimeout(bgAnimateTimer);
      bgAnimateTimer = setTimeout(function () {
        clearTimeout(bgAnimateTimer);
        bgAnimateTimer = setTimeout(function () {
    
          document.querySelector('.nice-block').classList.toggle('animated');
    
          //jQuery alternative is:
          // $('.nice-block').toggleClass('animated');
    
          animateBg ();
        }, 5000); //5 seconds for the animation effect
      }, 2500); //2.5 seconds between each animation
    }
    
    animateBg ();
    

    This improved performace in my case by ~15 times.

    (i) Note to calculate seconds for transition and timeouts correctly both in css and js if you want values different from 5 seconds.

提交回复
热议问题