使用重复的线性渐变颜色填充SVG元素

Cut*_*nja 7 html javascript css svg d3.js

我有一个SVG元素 - 一个矩形.

现在,为了对这个元素着色,我使用fill适用于任何颜色的属性.

现在,我试图通过使用此属性为它赋予条纹颜色

fill: repeating-linear-gradient(-45deg, #cc2229, #ffffff 4px, #cc2229 2px, #ffffff 8px);
Run Code Online (Sandbox Code Playgroud)

当分配给background属性时,这适用于普通DOM元素.

但是,它不适用于SVG元素.

我怎样才能实现这一目标?

在此输入图像描述 - 这就是我尝试SVG元素的样子(我正在使用d3.js)

小智 16

更好的解决方案:

http://jsfiddle.net/mcab43nd/14/

<svg>

<defs>

  <pattern id="pattern"
           width="8" height="10"
           patternUnits="userSpaceOnUse"
           patternTransform="rotate(45 50 50)">
    <line stroke="#a6a6a6" stroke-width="7px" y2="10"/>
  </pattern>

</defs>

<rect x="5" y="5"
      width="1000" height="25"
      fill= "url(#pattern)"
      opacity="0.4"
      stroke="#a6a6a6"
      stroke-width="2px" />

</svg>
Run Code Online (Sandbox Code Playgroud)


Cut*_*nja 5

http://jsfiddle.net/mcab43nd/1/ - 解决方案在这里

感谢 Lars 和 AmeliaBR

这是代码

<svg>

<defs>
   <linearGradient id="Gradient-1"x1="3%" y1="4%" x2="6%" y2="6%">
     <stop offset="0%" stop-color= "red" />
     <stop offset="50%" stop-color= "white" />
   </linearGradient>

   <linearGradient id="repeat"xlink:href="#Gradient-1"spreadMethod="repeat" />
</defs>

<rect x="30" y="10"
      width="200" height="100"
      fill= "url(#repeat)"
      stroke="red"
      stroke-width="2px" />
</svg>
Run Code Online (Sandbox Code Playgroud)

  • 没有理由使用 2 个渐变,只需将 spreadMethod 移动到第一个并直接使用它。 (3认同)