2

I have an SVG path, that needs to be filled with background image like this: enter image description here

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?

  • I have a hunch on what might be the issue but first, can you post a minimal reproducible example, perhaps through CodeSandbox? That will allow me to quickly figure out what might be the issue. – Harley Lang Sep 11 '20 at 16:17
  • 1
    @HarleyLang sure, here it is: https://codesandbox.io/s/nice-rhodes-djruu?file=/src/App.js – Michael Shkarubski Sep 11 '20 at 16:36

1 Answers1

1

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:

Harley Lang
  • 2,063
  • 2
  • 10
  • 26