前端常用的动画,不外乎以下几种:
纯JS实现
利用setInterval() 或者setTimeout() 方法,来持续修改某个元素的CSS属性,来达到样式变化的目的。
<script>
let element = document.getElementById('rect');
element.onclick = function (e) {
animation();
};
let animation = function () {
let move = 0;
let timer = setInterval(function () {
if (move > 200) {
clearInterval(timer);
} else {
move += 5;
element.style.marginLeft = move + "px";
console.log(move);
}
}, 16)
}
</script>
缺点:该方式会重复的导致页面的重绘和重排,性能消耗比较大,一般用于PC浏览器,移动端会有明显卡顿。
16ms = 1000ms/60帧 , 可视为近似流畅
SVG animation
SVG 标签简介
SVG实现动画,常见的有五个标签:
1 <set>
: 无动画,常用来实现延时操作
<svg width="320" height="320" xmlns="http://www.w3.org/2000/svg">
<g>
<text font-family="microsoft yahei" font-size="120" y="160" x="160">
马
<set attributeName="x" attributeType="XML" to="60" begin="3s" />
</text>
</g>
</svg>
2 <animate>
: 单属性动画,修改元素的一个属性。
<svg width="320" height="320" xmlns="http://www.w3.org/2000/svg">
<g>
<text font-family="microsoft yahei" font-size="120" y="160" x="160">
马
<animate attributeName="x" from="160" to="60" begin="0s" dur="3s" repeatCount="indefinite" />
</text>
</g>
</svg>
3 <animateColor>
: 颜色动画,已废弃
4 <animateTransform>
: 变换动画,同CSS3 的transform 常见的有rotate, skew, scale, translate等、
<svg width="320" height="320" xmlns="http://www.w3.org/2000/svg">
<g>
<text font-family="microsoft yahei" font-size="80" y="100" x=