Next.js Discord

Discord Forum

Reusable SVG mask component

Unanswered
Border Terrier posted this in #help-forum
Open in Discord
Border TerrierOP
Hey, I'm trying to create a reusable svg mask component which allows me to pass the image and the svg mask into as parameters. A lot of the tutorials I've found just don't seem to work. I'm using tailwind CSS, to make things easier and I want to ensure I keep the original svg file intact (vs stripping it down to just the path).

This is what I have so far:

import React from "react"
type MaskedImageProps = {
    svgShape?: React.ReactNode
    imageSrc: any
    maskId?: string
}

const MaskedImage = ({
    svgShape,
    imageSrc,
    maskId = "mask",
}: MaskedImageProps) => {

// for extracting the path from the unedited svg file
 const extractPath = (svgString) => {
  const parser = new DOMParser();
  const svgDoc = parser.parseFromString(svgString, 'image/svg+xml');
  const pathElement = svgDoc.querySelector('path');
  return pathElement ? pathElement.outerHTML : '';
};
const pathString = extractPath(svgString);

return (
  <svg 
    width="100%"    
    height="100%" 
    viewBox="0 0 100 100"
  >
    <defs>
      <clipPath 
         id={maskId}
clipPathUnits="objectBoundingBox"
      >
        <path                          d="M0 210.338L314 0V507.419L0 709V210.338Z"              fill="transparent"
         />
       </clipPath>
     </defs>
        
     <image
       href={imageSrc.src}
       width="100%"
       height="100%"
       mask={`url(#${maskId})`}
      />
   </svg>
)};

0 Replies