Search code examples
htmlsvgclip-path

How do I make this SVG background use clip path to make it transparent?


I have this svg I found online that I would like to use as a background but I would like to alter it so that the lines created by the are used in a clip-path, making them transparent and showing the background through the pattern.

I have no experience with svgs and clip paths so I don't know what to try. The end goal is to have this pattern but with the lines produced in being clipped or transparent from a rect.

    <svg id='patternId' width='100%' height='100%' xmlns='http://www.w3.org/2000/svg'>
        <defs>
            <pattern id='a' patternUnits='userSpaceOnUse' width='69.141' height='40' patternTransform='scale(2) rotate(0)'>
                <rect x='0' y='0' width='100%' height='100%' fill='rgb(54, 54, 54)'/>
                <path d='M69.212 40H46.118L34.57 20 46.118 0h23.094l11.547 20zM57.665 60H34.57L23.023 40 34.57 20h23.095l11.547 20zm0-40H34.57L23.023 0 34.57-20h23.095L69.212 0zM34.57 60H11.476L-.07 40l11.547-20h23.095l11.547 20zm0-40H11.476L-.07 0l11.547-20h23.095L46.118 0zM23.023 40H-.07l-11.547-20L-.07 0h23.094L34.57 20z'  stroke-width='1' stroke='rgb(150, 0, 0)' fill='none'/>
            </pattern>
        </defs>
        <rect width='800%' height='800%' transform='translate(-44,0)' fill='url(#a)'/>
    </svg>

Solution

  • Here is how I was able to achieve what I was after.
    First I had to use a Mask rather than a clip-path as I previously thought. Next I had to set the stroke of the path to black so that the mask would make the outlines transparent, then set the fill to white so they are solid. I applied the mask to a rect and set its fill to a color I wanted the squares to be. Wrap this all the original pattern and apply the pattern to another rect for display.

    This can be seen in action in the original Codepen https://codepen.io/PantheraDigital/pen/RwvzVej

    <svg viewBox="0 0" width='100%' height='100%' xmlns="http://www.w3.org/2000/svg">
      <defs>
        <pattern id="myPattern" patternUnits='userSpaceOnUse' width='69.141' height='40' patternTransform='scale(2) rotate(0)'>
          <mask id="myMask">
            <path
              d='M69.212 40H46.118L34.57 20 46.118 0h23.094l11.547 20zM57.665 60H34.57L23.023 40 34.57 20h23.095l11.547 20zm0-40H34.57L23.023 0 34.57-20h23.095L69.212 0zM34.57 60H11.476L-.07 40l11.547-20h23.095l11.547 20zm0-40H11.476L-.07 0l11.547-20h23.095L46.118 0zM23.023 40H-.07l-11.547-20L-.07 0h23.094L34.57 20z'
              fill="white" stroke-width='2' stroke='black' />
          </mask>
    
          <rect x="0" y="0" width="100%" height="100%" fill="purple" mask="url(#myMask)" />
        </pattern>
      </defs>
    
      <rect x="0" y="0" width="100%" height="100%" fill="url(#myPattern)"/>
    </svg>