我使用 SMIL 为 SVG 图像制作动画,然后将该图像用作 DOM 元素(例如,按钮
)的背景。
例如,这张 SVG 图像 ( http://mattstuehler.com/spinner.svg )
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40">
<g fill="none" stroke="#1e81cc" stroke-width="4">
<circle cx="50%" cy="50%" r="18" stroke-opacity="0.3"/>
<path d="M20,2 A18,18 0 0,1 38,20">
<animateTransform attributeName="transform" type="rotate" from="0 20 20" to="360 20 20" dur="1s" repeatCount="indefinite"/>
</path>
</g>
</svg>
但是,既然 SMIL 已被弃用,您将如何仅使用 CSS 来做到这一点?
提前致谢!
button {
width: 200px;
height: 60px;
background-color: #eee;
background-image: url(http://mattstuehler.com/spinner.svg);
background-repeat: no-repeat;
background-position: center center;
background-size: 50px 50px;
border: none;
-webkit-appearance: none;
}
<button>Hello</button>
最佳答案
更新:
Chrome have suspended deprecation of SMIL for now. More here
一种方法是使用 CSS 动画。动画 path
元素并修复 transform-origin
在微调器的中心。
因为我们可以有一个 <style>
SVG 元素中的标记,我们将此动画嵌入到 SVG 本身。
CSS 动画/SVG:
<svg height="40" viewbox="0 0 40 40" width="40" xmlns="http://www.w3.org/2000/svg">
<style>
path {
-webkit-animation: rotate 1s linear infinite;
-moz-animation: rotate 1s linear infinite;
animation: rotate 1s linear infinite;
transform-origin: 20px 20px;
}
@-webkit-keyframes rotate {
100% {
transform: rotate(360deg)
}
}
@keyframes rotate {
100% {
transform: rotate(360deg)
}
}
</style>
<g fill="none" stroke="#1e81cc" stroke-width="4">
<circle cx="50%" cy="50%" r="18" stroke-opacity="0.3"></circle>
<path d="M20,2 A18,18 0 0,1 38,20"></path>
</g>
</svg>
使用上面的 SVG 作为背景:
button {
width: 200px;
height: 60px;
background-color: #eee;
background-image: url(https://dl.dropboxusercontent.com/s/8j3gd6jfujxz2xg/spinner.svg);
background-repeat: no-repeat;
background-position: center center;
background-size: 50px 50px;
border: none;
}
<button>Hello</button>
注意:
某些浏览器可能会将动画 SVG 渲染为静态图像当用作背景时。指的是问题中的CSS方法和SMIL。
从版本 51 开始在 Chrome/Opera 和 Firefox 上运行良好。
关于javascript - 是否可以使用 CSS 在 DOM 元素上为 SVG 背景设置动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39670037/