Reputation: 91
I have an SVG path, that needs to be filled with background image like this:
I tried to find any ways to do it in Google and that's what I've found:
<div className="intro">
<p>Any text</p>
<svg fill="url(#pattern)">
<defs>
<pattern id="pattern">
<image href={introImage}/>
</pattern>
</defs>
<path d={path()}/>
</svg>
</div>
But it doesn't work, all I get is SVG with no background, although if I set fill="red"
it works.
I think that it doesn't work because of React, it is not just HTML after all... The link for the image is correct, the "d" attribute of path either, I've checked it any times.
So, how can I solve my problem?
Upvotes: 2
Views: 918
Reputation: 2333
It looks like your just missing a few attributes on your <svg>
namely the following:
<svg xmlns="/#pattern">
<defs>
<pattern
id="pattern"
patternUnits="userSpaceOnUse"
width="1200"
height="600"
> {/* <---- these attributes needed here */}
<image
href="https://api.time.com/wp-content/uploads/2018/05/forest-bathing.jpg?quality=85&w=1200&h=628&crop=1"
height={600}
width={1200}
x={0}
y={0}
/>
</pattern>
</defs>
<path
d="M0,214.7L282,0h433v399.5l-75.5,97.7l-224.2-49L308.4,557l-180.7-26.3L0,214.7z"
fill="url(#pattern)"
/> {/* ^---- fill your object with your image via class reference here! */}
</svg>
CodeSandbox Example: https://codesandbox.io/s/stack-custom-svg-path-w85cu?file=/src/App.js
Related question:
Funny how sometimes you google a question, only to find your own answer from the past!
Important to note that patternUnits="userSpaceOnUse"
is great for patterns with a BIG object and SMALLER repeating image. If you just want to fit an image to an object, patternUnits="objectBoundingBox"
may be a better fit. More info:
Upvotes: 1