html - 如何将图像设置为背景
问题描述
我试图在谷歌中找到任何方法来做到这一点,这就是我发现的:
<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”属性也是,我已经检查过它任何时候。
那么,我该如何解决我的问题呢?
解决方案
看起来您只是缺少以下几个属性<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"
则可能会更好。更多信息:
推荐阅读
- python - 图像数据 d_loss, g_loss = model_loss(input_images, input_z, data_shape[3]) 的尺寸无效
- time - 基于相对时间和位置的去重点数据
- python-xarray - 使用 Xarray 读取多个 Netcdf 文件时出现问题
- elasticsearch - ELK:情感分类
- flutter - 没有为“未来”类型定义吸气剂“长度”
- >'
- c# - Twitter API 上传媒体:代码 32:无法验证您的身份
- javascript - 如何使用 Vue 连接到 TLS?
- wordpress - 如何确保只有先登录主域才能进入子域?
- java - 通过spring boot从mysql数据库中检索时间
- html - 使用放大效果切换图像