实现动画的6种方案

通常,前端实现动画的方案主要有6种:CSS3 transition、CSS3 animation、Canvas动画、SVG动画、Javascript实现、requestAnimationFrame。

1. CSS3 transition

// html 
// css div{ position: absolute; left: 0; top: 0; width: 100px; height: 100px; background: pink; transition: all 1s ease-in-out; } .move{ left: 400px; background: red; } // js let timer = setTimeout(() => { let box = document.getElementById('box'); box.setAttribute('class', 'move'); },1000);

在移动端开发时,直接使用transition动画会让页面变慢,通常添加transform: translateZ(0)让动画过程更加流畅。

2. CSS3 animation

// html
// css div{ position: absolute; left: 0; top: 0; width: 100px; height: 100px; background: pink; animation: move 3s infinite; } @keyframes move { from { left: 0; } 50% { left: 400px; } to { left: 0; } }

3. Canvas动画

// html

// js
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let left = 0;
let timer = setInterval(() => {
    ctx.clearRect(0, 0, 600, 600);
    ctx.beginPath();
    ctx.fillStyle = 'pink';
    ctx.fillRect(left, 0, 100, 100);
    if (left > 500) {
        clearInterval(timer);
    }
    left++;
},16);

canvas动画只能在元素内部进行,超出则不显示

4. SVG动画


    
        
    

SVG动画跟Canvas动画类似,都只能在元素内部进行,超出则不显示。
SVG主要是通过SVG内部的配置来实现的,而Canvas要通过javascript的API实现

5. Javascript动画

// html
// css #box{ position: absolute; top: 0; left: 0; width: 100px; height: 100px; background: pink; } // js let box = document.getElementById('box'); let left = 0; let timer = setInterval(() => { if (left < window.innerWidth - 100) { box.style.left = left + 'px'; left ++; }else{ clearInterval(timer); } },16);

6. requestAnimationFrame

// html
// css #box{ position: absolute; top: 0; left: 0; width: 100px; height: 100px; background: pink; } // js window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame; let box = document.getElementById('box'); let left = 0; requestAnimationFrame(step); function step () { if(left < window.innerWidth - 100) { left += 1; box.style.left = left + 'px'; requestAnimationFrame(step); } }

requestAnimationFrame性能消耗比setInterval低一点,但是存在兼容性问题,移动端一般可以使用

你可能感兴趣的:(实现动画的6种方案)