是否可以使用CSS为DOM元素设置SVG背景动画?

时间:2016-09-23 21:49:01

标签: javascript html css svg

我使用SMIL为SVG图像设置动画,然后将该图像用作DOM元素的背景(例如,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>

但是,现在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>

2 个答案:

答案 0 :(得分:6)

更新:

  

目前,Chrome暂停了对SMIL的弃用。更多constructor

一种方法是使用CSS动画。动画path元素并将transform-origin固定在微调器的中心。

由于我们可以在SVG元素中添加here标记,因此我们在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 适用于Chrome / Opera和Firefox的51版。

答案 1 :(得分:2)

您可以使用任何静态PNG / WebP / JPG图像作为按钮的伪类的背景,然后通过CSS旋转它。

@keyframes btn_rotate {
  from {transform: rotate(0deg);}
  to {transform: rotate(360deg);}
} 

button::before {
  content: '';
  display: block;
  height: 60px;
  width: 60px;
  background: url(http://www.freeiconspng.com/uploads/spinner-icon-17.png);
  background-size: contain;
  position: absolute;
  left: calc(50% - 30px);
  top: calc(50% - 30px);
  animation: btn_rotate 2s infinite;
  animation-timing-function: linear;
}

button {
  width: 200px;
  height: 60px;
  background-color: #eee;
  border: none;
  position: relative;
  overflow: hidden;
}
<button>Hello</button>