CSS and JS for continuous animation

I saw a question when browsing the forum, how does JS achieve continuous animation effect? The first thing that came to my mind was timer. Later, when I saw someone mentioned requestAnimationFrame, I went to look it up because I didn’t know anything about it before, and also recorded the use of animation.

animation(CSS)

Compatibility and Attributes

Click here to see compatibility

  • Animation-name: indicates the animation name
  • Animation-duration: animation duration
  • Animation-timing-function: animation execution mode
  • Animation-delay: indicates the animation delay
  • Animation-rotund-count: number of animation executions
  • Animation-direction: indicates whether the animation is executed in reverse direction
  • Animation-fill-mode: style before and after animation execution

The instance

Jsfiddle preview

.box { width: 200px; height: 200px; background-color: aqua; position: absolute; left: 0; top: 0; animation: test 3s linear 2s infinite; } @keyframes test { from { } to { width: 50px; height: 50px; background-color: red; Opacity: 0.5; left: 500px; top: 500px; }}Copy the code
<div class="box"></div>Copy the code

requestAnimationFrame(JS)

Compatibility and basic concepts

Click here to see compatibility

Advantage:

  • Browsers can optimize parallel animation sequences, rearrange sequences more sensively, and combine actions within a single rendering cycle for smoother animation
  • Once the page is not in the browser’s current TAB, the refresh automatically stops. This saves CPU, GPU and power

Use:

Just keep calling requestAnimFrame

CancelAnimationFrame can be used to clear the animation

For example,

Jsfiddle preview

#anim {
  position: absolute;
  left: 0px;
  width: 150px;
  height: 150px;
  line-height: 150px;
  background: aqua;
  color: white;
  border-radius: 10px;
  padding: 1em;
}Copy the code
<div id="anim"> Click here to start animation</div>Copy the code
/ / compatibility processing window. RequestAnimFrame = (function () {return (window. RequestAnimationFrame | | window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback, element) { window.setTimeout(callback, 1000 / 60) } ) })() var elem = document.getElementById('anim') var startTime = undefined function render(time) { time = Date.now() if (startTime === undefined) { startTime = time } elem.style.left = ((time - startTime) / 10) % 300 + 'px' elem.style.top = ((time - startTime) / 10) % 300 + 'px' elem.style.borderRadius = ((time - startTime) / 10) % 300 + 'px'  elem.style.opacity = Math.floor((time - startTime / 100)) % 2 === 0 ? 1:0.3} ele. onclick = function() {(function () {render() requestAnimFrame(animloop, elem)})()}Copy the code

reference

requestAnimationFrame MDN

requestanimationframe

animation MDN