没有defs的SVG中的线性渐变

时间:2011-09-30 17:56:49

标签: svg gradient linear-gradients

我可以在SVG中使用线性渐变,其中defs-section如下:

<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink">

  <defs>
    <linearGradient id="myLinearGradient1"
                    x1="0%" y1="0%"
                    x2="0%" y2="100%"
                    spreadMethod="pad">
      <stop offset="0%"   stop-color="#00cc00" stop-opacity="1"/>
      <stop offset="100%" stop-color="#006600" stop-opacity="1"/>
    </linearGradient>
  </defs>

  <rect x="0" y="0" width="100" height="100"
     style="fill:url(#myLinearGradient1)" />

</svg>

我可以使用没有defs-section的线性渐变吗?我发现这样的事情:

<rect style="fill:lineargradient(foo)">

2 个答案:

答案 0 :(得分:3)

<defs>仅用于结构化目的,其中的元素不会显示,但由于渐变只有在应用于形状或其他元素时才可见,您可以在文档的任何位置定义它

但你还是要坚持正确的语法:

<rect style="fill:url(#myLinearGradient1)" ... />

答案 1 :(得分:0)

是的,您确实可以拥有一个渐变而无需defs元素;您只需将渐变元素放在代码中的其他任何地方,例如:

<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink">

  <linearGradient id="myLinearGradient1"
                x1="0%" y1="0%"
                x2="0%" y2="100%"
                spreadMethod="pad">
    <stop offset="0%"   stop-color="#00cc00" stop-opacity="1"/>
    <stop offset="100%" stop-color="#006600" stop-opacity="1"/>
  </linearGradient>

  <rect x="0" y="0" width="100" height="100"
     style="fill:url(#myLinearGradient1)" />

</svg>