首页 > 解决方案 > SVG 填充路径动画

问题描述

我有一条带箭头的路径,我想做一个从左到右的颜色过渡动画。

我已经为线和箭头做了这个,但它似乎不同步。我希望线条和箭头无缝过渡到两种颜色。

这是小提琴:https ://jsfiddle.net/afonsolfm/6ojwrksd/ 。

HTML

<svg>
  <defs>
      <linearGradient id="left-to-right">
        <stop offset="0" stop-color="green">
          <animate dur="2s" attributeName="offset" fill="freeze" from="0" to="1" />
        </stop>
        <stop offset="0" stop-color="blue">
          <animate dur="0s" attributeName="offset" fill="freeze" from="0" to="1" />
        </stop>
      </linearGradient>

      <linearGradient id="left-to-right-arrow">
        <stop offset="0" stop-color="green">
          <animate begin="2s" dur="1s" attributeName="offset" fill="freeze" from="0" to="1" />
        </stop>
        <stop offset="0" stop-color="blue">
          <animate dur="2s" attributeName="offset" fill="freeze" from="0" to="1" />
        </stop>
      </linearGradient>

    <marker id="arrow-head" viewBox="-5 -5 10 10" refX="0" refY="0" orient="auto" markerWidth="10" markerHeight="10">
      <path d="M -5 5, 0 0.3, -5 -5"></path>
    </marker>
  </defs>
  <path class="line" d="M 10 100 A 500 500 0 0 1 500 100"></path>
</svg>

CSS

svg {
  width: 600px;
  height: 300px;
  border: 1px solid green;
}

path {
  fill: transparent;
}

.line {
  marker-end: url(#arrow-head);
  stroke: url(#left-to-right);
  stroke-width: 10px;
}

#arrow-head {
  stroke: url(#left-to-right-arrow);
}

标签: csssvg

解决方案


另一种方法是将渐变动画放在矩形上,然后将箭头用作遮罩。

svg {
  width: 600px;
  height: 300px;
  border: 1px solid green;
}

path {
  fill: transparent;
}

.line {
  marker-end: url(#arrow-head);
  stroke: white;
  stroke-width: 10px;
}

#arrow-head {
  stroke: white;
}

#masked-rect {
  fill: url(#left-to-right);
  mask: url(#arrow-mask);
}
<svg>
  <defs>
    <linearGradient id="left-to-right">
      <stop offset="0" stop-color="green">
        <animate dur="2s" attributeName="offset" fill="freeze" from="0" to="1" />
      </stop>
      <stop offset="0" stop-color="blue">
        <animate dur="0s" attributeName="offset" fill="freeze" from="0" to="1" />
      </stop>
    </linearGradient>
    
    <marker id="arrow-head" viewBox="-5 -5 10 10" refX="0" refY="0" orient="auto" markerWidth="10" markerHeight="10">
      <path d="M -5 5, 0 0.3, -5 -5"></path>
    </marker>
    
    <mask id="arrow-mask">
      <path class="line" d="M 10 100 A 500 500 0 0 1 500 100"></path>
    </mask>
  </defs>
  
  <rect id="masked-rect" width="100%" height="100%"/>
</svg>


推荐阅读