时间图表:SMIL 动画的蓝图
Email Newsletter
电子邮件通讯
Weekly tips on front-end & UX.
Trusted by 182,000+ folks.
每周前端与 UX 技巧。
深受 182,000 多人的信赖。
Discover SMIL, the often-overlooked way to animate SVGs that works inside <img> tags and can fully animate everything in an SVG without JavaScript.
探索 SMIL,这是一种经常被忽视的 SVG 动画制作方式,它可以在 <img> 标签内运行,并且无需 JavaScript 即可完全为 SVG 中的所有内容添加动画。
We know that everything on the web is a box by default, but you’ll find many animated <div>s pretending to be circles. But if you’ve ever met a real <circle>, you’ll know that they’ve got a lot more going for them. Dressed in SVG, they fit into a wider range of crowds than a humble <div> wearing HTML/CSS can. <img> has a strict no .html policy.
我们知道,Web 上的所有内容默认都是盒子,但你会发现许多带有动画的 <div> 伪装成圆形。但如果你见过真正的 <circle>,你就会知道它们有更多的优势。穿上 SVG 的外衣,它们能融入的圈子比穿着 HTML/CSS 的普通 <div> 要广得多。<img> 有着严格的禁止 .html 策略。
The <img> tag is not as static as its name suggests. Any embedded JavaScript unfortunately won’t run if you load an SVG file with an <img> tag, but CSS animations work perfectly fine. Many of the SVG attributes do have CSS property counterparts, and the geometry properties have been supported across the major browsers since 2024. Some attributes that you might want to animate, like viewBox, don’t have equivalents yet.
<img> 标签 并不像其名称暗示的那样静态。遗憾的是,如果你使用 <img> 标签加载 SVG 文件,任何嵌入的 JavaScript 都不会运行,但 CSS 动画可以完美运行。许多 SVG 属性 确实有对应的 CSS 属性,并且自 2024 年以来,几何属性 已在各大主流浏览器中得到支持。一些你可能想要设置动画的属性,如 viewBox,目前还没有对应的等效属性。
Besides JavaScript and CSS, there’s another way to animate SVGs: Synchronized Multimedia Integration Language (SMIL). Despite its quirks, it’s still worth learning. Like CSS animations, SMIL animations also work in <img> tags and can fully animate everything in an SVG, without JavaScript.
除了 JavaScript 和 CSS,还有另一种为 SVG 添加动画的方式:同步多媒体集成语言(SMIL)。尽管它有些古怪,但仍然值得学习。与 CSS 动画类似,SMIL 动画也可以在 <img> 标签中工作,并且可以完全为 SVG 中的所有内容添加动画,无需 JavaScript。
If you’ve never heard of SMIL or need a refresher, check out Andy Clarke’s well-named article. Then we’ll look at a way to plan an animation and make SMIL markup mor...