【问题标题】:Is it possible to animate stroke gradient?是否可以为描边渐变设置动画?
【发布时间】:2018-11-03 22:57:05
【问题描述】:

是否可以为矩形/圆形/闭合路径设置渐变动画? 此示例仅在两个渐变之间进行硬切换

Codepen

SVG - 带有两个已定义渐变的圆和路径

<svg width="900" height="500" viewBox="0 0 300 300">
  <defs>

    <linearGradient id="gradient1" x1="0%" y1="0%" x2="0%" y2="100%">
      <stop offset="0%" stop-color="#00bc9b" />
      <stop offset="100%" stop-color="#5eaefd" />
    </linearGradient>
    <linearGradient id="gradient2" x1="0%" y1="0%" x2="0%" y2="100%">
      <stop offset="0%" stop-color="#333" />
      <stop offset="100%" stop-color="#fff" />
    </linearGradient>

  </defs>

  <path transform="translate(-200,-200)" d="M 100 300 Q 150 50 200 250 Q 250 550 350 350 Q 350 50 400 250 C 450 550 450 50 500 300 C 550 50 550 550 600 300 A 50 50 0 1 1 100 300 " />
  <circle cx="200" cy="200" r="200" />

</svg>

CSS

circle, path {
  stroke: red;
  stroke-width: 20px;
  fill: transparent;
  animation-name: stroke;
  animation-duration: 1s;
  animation-direction: alternate;
  animation-iteration-count: infinite;
  animation-timing-function: ease-in-out;
}


@keyframes stroke {
  from {
    stroke: url(#gradient1);
  }
  to {
    stroke: url(#gradient2);
  }
}

【问题讨论】:

  • 如果 CSS 做不到,JavaScript 肯定可以。您对 JavaScript 答案感兴趣吗?
  • 我更喜欢 SVG/CSS,但如果不可能,请确定为什么不:)

标签: css svg css-animations


【解决方案1】:

尽管 IE 和 Edge 不支持 SMIL 动画,但您可以使用 SMIL 动画。

svg{width:90vh}
rect {
  stroke: url(#gradient1);
  }
<svg viewBox="0 0 500 300">
  <defs>
    <linearGradient id="gradient1" x1="0%" y1="0%" x2="0%" y2="100%">
      <stop offset="0%" stop-color="#00bc9b">
        <animate attributeName="stop-color" attributeType="CSS" values="#00bc9b;#333;#00bc9b;" dur="5s" repeatCount="indefinite"></animate>
      </stop>
      <stop offset="100%" stop-color="#5eaefd">
        <animate attributeName="stop-color" attributeType="CSS" values="#5eaefd;#f00;#5eaefd;" dur="5s" repeatCount="indefinite"></animate>
      </stop>
    </linearGradient>
   
  </defs>
  <rect width="400" height="200" x="10" y="20" 
        stroke-width="20" 
        fill="transparent"
        > 
  </rect>
</svg>

【讨论】:

  • 谢谢@RobertLongson 我不知道 FakeSmile。
猜你喜欢
  • 2018-10-02
  • 1970-01-01
  • 1970-01-01
  • 2015-10-22
  • 2012-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多