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

问题描述 投票:0回答:2

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

现在,要为该元素着色,我使用适用于任何颜色的

fill
属性。

现在,我尝试使用此属性为其赋予条纹颜色

fill: repeating-linear-gradient(-45deg, #cc2229, #ffffff 4px, #cc2229 2px, #ffffff 8px);

当分配给

background
属性时,这适用于普通 DOM 元素。

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

我怎样才能做到这一点?

enter image description here - 这就是我尝试 SVG 元素的样子(我正在使用 d3.js)

javascript html css svg d3.js
2个回答
25
投票

更好的解决方案:

<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>


6
投票

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

感谢拉尔斯和阿米莉亚BR

这是代码

<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>
© www.soinside.com 2019 - 2024. All rights reserved.