mat*_*ler 5 html javascript css svg
我使用SMIL为SVG图像设置动画,然后将该图像用作DOM元素的背景(例如,a button).
例如,此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>
Run Code Online (Sandbox Code Playgroud)
但是,现在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;
}Run Code Online (Sandbox Code Playgroud)
<button>Hello</button>Run Code Online (Sandbox Code Playgroud)
更新:
Chrome暂时暂停了对SMIL的弃用.更多这里
一种方法是使用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>Run Code Online (Sandbox Code Playgroud)
使用上面的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;
}Run Code Online (Sandbox Code Playgroud)
<button>Hello</button>Run Code Online (Sandbox Code Playgroud)
注意:
某些浏览器在用作背景时可能会将动画SVG渲染为静态图像.指问题中的CSS方法和SMIL.
适用于Chrome/Opera和Firefox版本51.