CSS3渐变作为SVG

6

在我的页面上,我使用了很多CSS3渐变。我想为IE和Opera提供一些SVG回退方案。

对于CSS3的线性渐变,创建SVG替代方案非常简单。我使用以下代码:

   <svg xmlns="http://www.w3.org/2000/svg">
     <linearGradient id="g" gradientTransform="rotate(90,.5,.5)">
       <stop stop-color="black" offset="0"/>
       <stop stop-color="white" offset="1"/>
     </linearGradient>
     <rect x="0" y="0" width="100%" height="100%" fill="url(#g)"/>
   </svg>

这相当于以下的CSS代码:
  background:-webkit-linear-gradient(black,white);
  background:   -moz-linear-gradient(black,white);
  background:     -o-linear-gradient(black,white);
  background:        linear-gradient(black,white);

现在,当涉及到CSS3径向渐变时,事情变得有点复杂。 我无法创建一个SVG等效于下面的CSS3径向渐变:

  background:-webkit-radial-gradient(50% 10%,circle,rgba(255,255,255,.3) 10%,rgba(255,255,255,0) 90%);
  background:   -moz-radial-gradient(50% 10%,circle,rgba(255,255,255,.3) 10%,rgba(255,255,255,0) 90%);
  background:     -o-radial-gradient(50% 10%,circle,rgba(255,255,255,.3) 10%,rgba(255,255,255,0) 90%);
  background:        radial-gradient(circle at 50% 10%,rgba(255,255,255,.3) 10%,rgba(255,255,255,0) 90%);

到目前为止,我已经想出了这个:

<svg xmlns="http://www.w3.org/2000/svg">
  <radialGradient id="g">
    <stop stop-opacity=".3" stop-color="white" offset=".1"/>
    <stop stop-opacity="0" stop-color="white" offset=".9"/>
  </radialGradient>
  <rect x="0" y="0" width="100%" height="100%" fill="url(#g)"/>
</svg>

但是它给我的结果不同。

我如何在CSS3中制作与原始渐变相同的渐变?

这是两种渐变的演示:http://jsfiddle.net/QuMnA/

1个回答

4

您需要指定径向渐变的cxcy属性...

<svg xmlns="http://www.w3.org/2000/svg">
  <radialGradient id="g" r="1" cx="50%" cy="10%">
    <stop stop-opacity=".3" stop-color="white" offset=".1"/>
    <stop stop-opacity="0" stop-color="white" offset=".9"/>
  </radialGradient>
  <rect x="0" y="0" width="100%" height="100%" fill="url(#g)"/>
</svg>

尝试调整radialGradient标签中的r属性,直到获得满意的结果,然后检查更新后的代码。 - methodofaction
现代浏览器支持SVG背景,因此如果您使用base64编码,则无需CSS3回退。 - methodofaction
很好,将半径设置为1可以得到想要的结果。谢谢! - Kuwiuwuw Kurwiow
@methodofaction,有没有一种方法可以在不使用radialGradient标签的情况下为SVG创建渐变? - Asking
@methodofaction,抱歉我想说的是linearGradient。我问这个问题是因为当我的React组件包含一个SVG在页面上被多次使用时,出现了“id属性值必须唯一”的问题。我查阅了许多文章,但没有找到解决方案。你知道如何避免这种情况吗?我想使用渐变来解决,但是使用CSS的background: ...对路径不起作用。 - Asking
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接