Search code examples
javascripthtmlcsssvgd3.js

Fill SVG element with a repeating linear gradient color


I have an SVG element - a rectangle.

Now, to color this element, I use fill attribute that works with any color.

Now, I am trying to give it a stripes color by using this property

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

This works for normal DOM elements when assigned to background attribute.

But, IT DOESN'T WORK WITH SVG ELEMENT.

How can i achieve that?

enter image description here - this is how i am trying my SVG element to look like (I am using d3.js)


Solution

  • Thanks to Lars and AmeliaBR

    Here is the code:

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