Search code examples
svgmaskclip-path

How can I use clip-path to achieve a text effect on my SVG in the browser?


I want to use clip-path to implement effect like: svg with text clip-path, but open in browser it just display an empty
svg. I wrap the path with <g> tag, then it failed.

<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32" fill="none" style="
    width: 200px;
    height:  200px;
">
    <defs>
        <clipPath id="text-path">
            <g clip-rule="evenodd" fill-rule="evenodd">
                <path d="M0 0H14V2H2V13H22V10H24V13H32V27H24V32H0V0ZM2 30V27H22V30H2Z"/>
                <path d="M16 0L24 8H16V0Z"/>
                <text x="7.5" y="23">PDF</text>
            </g>
        </clipPath>
    </defs>
    <g clip-path="url(#text-path)" fill="red">
        <path d="M0 0H14V2H2V13H22V10H24V13H32V27H24V32H0V0ZM2 30V27H22V30H2Z"/>
        <path d="M16 0L24 8H16V0Z"/>
    </g>

    <style>
        text {dominant-baseline: hanging;font-size: 8px;font-weight: bold;}
    </style>
</svg>

it should be displayed in browser.


Solution

  • In your example (above) you may remove the wrapping group around the 2 paths and the text and it would work.

     <clipPath id="text-path">
            <!-- <g clip-rule="evenodd" fill-rule="evenodd"> -->
                <path d="M0 0H14V2H2V13H22V10H24V13H32V27H24V32H0V0ZM2 30V27H22V30H2Z"/>
                <path d="M16 0L24 8H16V0Z"/>
                <text x="7.5" y="23">PDF</text>
            <!-- </g> -->
     </clipPath>
    

    However you won't see the text. If what you need is to see the text as a hole in the shapes you will need a mask where the text is black and the 2 paths are white. In the case of the mask you can use a group if you think you need it.

    <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32" style="
        width: 200px;
        height:  200px;
        background:silver">
      <mask id="m">
      <g fill="white">
        <path d="M0 0H14V2H2V13H22V10H24V13H32V27H24V32H0V0ZM2 30V27H22V30H2Z" />
        <path d="M16 0L24 8H16V0Z" />
      </g>
        <text x="7.5" y="23" fill="black">PDF</text>
      </mask>
    
      <rect width="32" height="32" mask="url(#m)" fill="red" />
    
      <style>
        text {
          dominant-baseline: hanging;
          font-size: 8px;
          font-weight: bold;
        }
      </style>
    
    </svg>