SVG中的动画有CSS动画、JS动画、基于GreenSock插件的动画。
一、CSS动画
<svg width="500" height="500" xmlns="http://www.w3.org/2000/svg" version="1.1">
<line id="line" x1="0" x2="500" y1="0" y2="0" stroke="orange" stroke-width="10" />
</svg>
svg {
display: block;
margin: 50px auto;
}
#line {
stroke-dasharray: 500;
stroke-dashoffset: 500;
animation: animation 2s linear infinite;
}
@keyframes animation {
to {
stroke-dashoffset: 0;
}
}
二、JS动画
<svg width="500" height="500">
<rect id="svg" x="0" y="0" width="100" height="100" fill="#ff770f" />
</svg>
const svgEl = document.getElementById('svg');
let x = 0,
y = 0,
add = true;
setInterval(() => {
x += 1;
if (y < 150 && add) {
y += 1;
} else {
add = false;
y -= 1;
}
console.log(`x: ${x}, y: ${y}`);
svgEl.setAttribute('transform', `translate(${x}, ${y})`);
}, 10);
三、GreenSock插件
GreenSock 动画平台 (GSAP) 是一个业界知名的工具套件,除了核心,还有各种插件。您无需学习它们即可开始,但它们可以帮助解决特定的动画挑战。
<div id="svg-wrapper">
<svg width="500" height="500" xmlns="http://www.w3.org/2000/svg">
<rect id="rect" width="50" height="50" fill="orange"></rect>
</svg>
</div>
<script src="https://cdn.jsdelivr.net/npm/gsap"></script>
<script>
gsap.to('#rect', {
x: 300, // transform: translateX(300px)
duration: 2 // 动画执行时间2S
})
</script>
视频讲解https://www.bilibili.com/video/BV1go4y1x7sk/?vd_source=be4efb0f2cfe5e83a1774731474196fd