Search code examples
javascripthtmlelectronchromium

CSS animation automatically goes to default


https://jsfiddle.net/t3w1Lqr0/1/
When I run this code it sometimes works as expected and sometimes glitches and goes to 0deg
See the gif Below ↓
I am using it for electron.
I works most of the time in jsfiddle but rarely works in electron.
Electron v13.1.2
Chromium v91.0.4472.77
Node v14.16.0

enter image description here


Solution

  • You could create your animation purely in CSS and Utilize animation-fill-mode: forwards; to preserve the last frame of the animation.

    * {
      box-sizing: border-box; margin: 0; padding: 0;
    }
    html, body { height: 100%; }
    body {
      display: flex; justify-content: center; align-items: center;
      background-color: #eee;
    }
    div, hr::before {
      overflow: hidden; position: absolute;
      width: 10rem; height: 5rem;
    }
    hr {
      border-style: solid; border-width: 1.5rem;
      border-color: #333; border-radius: 10rem;
      width: 10rem; height: 10rem;
    }
    hr::before {
      content: '';
      transform-origin: 50% 100%; transform: translateX( -50% );
      bottom: 0.25rem; left: 50%;
      border-radius: 100% 100% 0.5rem 0.5rem;
      width: 0.5rem; height: 4.5rem;
      background-color: #ccc;
      animation-name: rotate; animation-duration: 2s;
      animation-timing-function: ease-in-out;
      animation-fill-mode: forwards; /* Force last frame of animation to stay */
    }
    @keyframes rotate {
      0% { transform: translateX( -50% ) rotate( -90deg ); }
      100% { transform: translateX( -50% ) rotate( 90deg ); }
    }
    <div> <hr> </div>

    And if you want to add a delay before your animation starts playing as your JavaScript does you can use the CSS property animation-delay.