【发布时间】:2020-06-27 03:36:32
【问题描述】:
我正在尝试用 React 中的图像填充一个简单的圆形 SVG。我发现的资源没有帮助,因为它们似乎不适用于 JSX。
这是我目前拥有的代码:
import React, {Component} from 'react';
import Anime from '../images/Anime.jpeg';
class Circle extends Component {
render() {
return (
<div>
<svg height="300" width="300">
<circle cx="150" cy="150" r="100" stroke="black" stroke-width="3" fill={Anime} />
</svg>
</div>
);
}
}
export default Circle;
我的第一个直觉是调整fill 属性,将原始颜色="red" 替换为={Anime} 或=url("../images/Anime.jpeg"),但都不起作用。
(我知道动漫图像的路径是正确的,在通过在 div 内渲染 <img src={Anime} alt={Anime}></img> 对其进行测试之后。
我看到有人使用<defs> 和<pattern> 标签,因此(参考this post):
<svg id="graph" width="100%" height="400px">
<!-- pattern -->
<defs>
<pattern id="image" x="0%" y="0%" height="100%" width="100%"
viewBox="0 0 512 512">
<image x="0%" y="0%" width="512" height="512" xlink:href="https://cdn3.iconfinder.com/data/icons/people-professions/512/Baby-512.png"></image>
</pattern>
</defs>
<circle id="sd" class="medium" cx="5%" cy="40%" r="5%" fill="url(#image)" stroke="lightblue" stroke-width="0.5%" />
</svg>
但是这些标签似乎在 React / JSX 中不起作用;当我尝试使用它们时,我不断收到此错误:Namespace tags are not supported by default. React's JSX doesn't support namespace tags. You can turn on the 'throwIfNamespace' flag to bypass this warning.
有没有办法解决这个问题?我希望能够将下面的图片放入一个简单的圆形 svg 中,周围有一个粗黑边框。
【问题讨论】:
-
您可以使用
clip-path剪辑图像。 this article 中有一个例子,搜索“Using clip-path with an SVG-defined”。