【问题标题】:How to set image as a background for <svg> tag in React.js?如何在 React.js 中将图像设置为 <svg> 标签的背景?
【发布时间】:2020-12-30 04:04:30
【问题描述】:

我有一个 SVG 路径,需要用这样的背景图像填充:

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

      <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”属性也是正确的,我已经检查过。

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

【问题讨论】:

  • 我有预感可能是什么问题,但首先,您能否发布一个最小的可重现示例,也许是通过 CodeSandbox?这将使我能够快速找出问题所在。
  • @HarleyLang 当然,这里是:codesandbox.io/s/nice-rhodes-djruu?file=/src/App.js

标签: html css reactjs svg


【解决方案1】:

您的&lt;svg&gt; 似乎只是缺少一些属性,即:

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

代码沙盒示例:https://codesandbox.io/s/stack-custom-svg-path-w85cu?file=/src/App.js


相关问题:


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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-29
    • 2021-02-15
    • 1970-01-01
    • 2014-04-07
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    相关资源
    最近更新 更多