通常,前端实现动画的方案主要有6种:CSS3 transition、CSS3 animation、Canvas动画、SVG动画、Javascript实现、requestAnimationFrame。
1. CSS3 transition
// html
<div id="box"></div>
// 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
<div id="box"></div>
// 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
<canvas id="canvas" width="600" height="600"></canvas>
// 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动画只能在<canvas>元素内部进行,超出则不显示
4. SVG动画
<svg id="box" width="600" height="600" version="1.1" xmlns="http://www.w3.org/2000/svg">
<rect width="100" height="100" style="fill:pink;">
<animate attributeName="x" from="0" to="400" dur="3s" repeatCount="indefinite" />
</rect>
</svg>
SVG动画跟Canvas动画类似,都只能在<canvas>元素内部进行,超出则不显示。
SVG主要是通过SVG内部的配置来实现的,而Canvas要通过javascript的API实现
5. Javascript动画
// html
<div id="box"></div>
// 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
<div id="box"></div>
// 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低一点,但是存在兼容性问题,移动端一般可以使用