从左到右填充svg

Fill svg from left to right

我是 svg 的新手,我试图在 path/circle 中填充颜色。我能够用过渡来填充它。

但我想知道有没有办法从 path/circle.

的左到右填充 svg

SVG

<svg viewBox="0 0 160 160" width="160" height="160">
  <circle cx="80" cy="80" r="50" />
</svg>

CSS

circle {
  transition: all 3s;
}

JS

setTimeout(function(){
  $('circle').css('fill', 'red');
},300);

如何按特定方向填充,例如从左到右?

Codepen

由于 "fill left to right" 有很多含义,我举了几个例子:

移动渐变:

我建议使用 SVG <linearGradient><animate> 标签。这样你就不需要 JS 或 CSS.

这是在 SVG 中设置渐变动画的指南:http://designmodo.com/animate-svg-gradients/ 以及一般的 SVG 动画:https://css-tricks.com/guide-svg-animations-smil/

在你的情况下(从左到右填写),我会这样做:

<svg viewBox="0 0 160 160" width="160" height="160">
    <defs>
        <linearGradient id="lightGradient">
            <stop offset="0%" stop-color="red">
                <animate attributeName="stop-color" values="black; red" dur="3s" fill="freeze" /> 
            </stop>
            <stop offset="100%" stop-color="black">
                <animate attributeName="stop-color" values="black; red" dur="3s" fill="freeze" begin="3s"/> 
            </stop>
        </linearGradient>
    </defs>
    <circle cx="80" cy="80" r="50" fill="url(#lightGradient)"/>
</svg>

从技术上讲这是作弊,因为渐变实际上并没有移动,但是两边的颜色发生了变化,但看起来几乎一样。它以从黑色到黑色的渐变开始,然后左侧变为红色,给人一种红色从左侧移入的错觉。左边变红后,右边由黑变红,看起来渐变在移动,填满了整个圆

清除左右边框:

最好为此使用 <clip-path>

<clipPath id="left-to-right">
    <rect x="130" y="30" width="0" height="100" >
        <animate attributeName="width" values="0;100" dur="3s" fill="freeze"/>   
    </rect>
</clipPath>
...
<circle cx="180" cy="80" r="50" fill="black"/>
<circle cx="180" cy="80" r="50" fill="red" clip-path="url(#left-to-right)"/>

这个画了一个黑色圆圈,然后在一个不断增长的裁剪区域内画了一个红色圆圈。

一个圆圈遮住另一个圆圈:

同样,<clip-path> 适用于此:

<clipPath id="steady">
    <circle cx="280" cy="80" r="50"/>
</clipPath>
...
<circle cx="280" cy="80" r="50" fill="red" clip-path="url(#steady)">
    <animate attributeName="cx" values="180;280" dur="3s" fill="freeze"/>
</circle>

这个使用圆形裁剪区域并在其中移动第二个圆圈。

在 Codepen 中:http://codepen.io/anon/pen/aOKeYQ

这是可能的,但不是仅使用 'fill'。

例如,您可以进行线性渐变填充,有两个停靠点,一个是您想要的颜色,另一个是完全透明的。然后为第二个梯度停止的 offset 设置动画。有关示例,请参见 here.

另一种方法是使用 clip-path,其中剪辑形状是 rect 动画,例如从左到右。然后可以将其应用于您要像这样填充的形状的副本。基本上你需要起始形状(未填充)和结束形状(填充),最终形状通过动画剪辑路径显示。