How do I use a stroke as a clipping path in SVG?

1.4k views Asked by At

I have a path like the following:

<path class="path" d="M0,550L0,366.6666666666667C0,366.6666666666667,95.43389463154384,198.61111111111114,143.31860620206734,183.33333333333337C191.20331777259085,168.0555555555556..."></path>

This shows on my page as so:

Path

I'd like for this to be the clipping path against which I display a set of rectangles. I've currently got it to look like this:

Path as clipPath

However, I would like for it to nonetheless be a 2px line, that changes color when it goes into the realm of a new <rect>. I'm currently thinking of approaching this by somehow making the stroke of the path into the <clipPath>, but I'm open to other methods of getting this working as well.

1

There are 1 answers

0
Paul LeBeau On BEST ANSWER

A <clipPath> is the wrong approach for this case. The correct solution is to use a <mask>.

<svg width="500" height="240">

  <defs>
    <mask id="graph">
      <path d="M 0,150 L 100,20 L 200,210 L 300,100 L 400,130 L 500,50"
            fill="none" stroke="white" stroke-width="4"/>
    </mask>
  </defs>

  <g mask="url(#graph)">
    <rect y="0" width="500" height="60" fill="red"/>
    <rect y="60" width="500" height="60" fill="blue"/>
    <rect y="120" width="500" height="60" fill="green"/>
    <rect y="180" width="500" height="60" fill="yellow"/>
  </g>
</svg>