首页 > 解决方案 > 如何将图像设置为背景 tag in React.js?

问题描述

我有一个 SVG 路径,需要用这样的背景图像填充: 在此处输入图像描述

我试图在谷歌中找到任何方法来做到这一点,这就是我发现的:

      <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>

但它不起作用,我得到的只是没有背景的 SVG,尽管如果我设置fill="red"它可以工作。

我认为它不起作用是因为 React,它毕竟不仅仅是 HTML ......图像的链接是正确的,路径的“d”属性也是,我已经检查过它任何时候。

那么,我该如何解决我的问题呢?

标签: htmlcssreactjssvg

解决方案


看起来您只是缺少以下几个属性<svg>

          <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 示例:https ://codesandbox.io/s/stack-custom-svg-path-w85cu?file=/src/App.js


相关问题:


有趣的是,有时你用谷歌搜索一个问题,却从过去找到你自己的答案!

需要注意的patternUnits="userSpaceOnUse"是,这对于具有大对象和较小重复图像的图案非常有用。如果您只想将图像适合对象,patternUnits="objectBoundingBox"则可能会更好。更多信息:


推荐阅读