我正在用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,并在其周围带有黑色粗边框。
[我想出了一种方法,想发布/共享它,以防万一有人在这里,看着这篇文章,想知道解决方案(其中的一种)!
这是我的最终代码:
import React, {Component} from 'react';
import AnimeCropped from '../images/AnimeCropped.png';
class Circle extends Component {
render() {
return (
<div>
<svg height="670" width="670">
<circle cx="350" cy="350" r="300" stroke="black" stroke-width="5" fill="none" />
<image className='img-circle' xlinkHref={AnimeCropped} x='75.5' y="15" height="670" width="670"/>
</svg>
</div>
);
}
}
export default Circle;
基本上是我做的:
将照片裁剪为圆形。我本可以遵循cubrr的建议并对其进行剪切路径(这是一个好主意!),但是-我只是在网上找到并使用了照片裁剪工具。然后,我将新裁剪的图片命名为“ AnimeCropped”,并将其保存在同一目录中。
将图片导入组件文件,并在<image>
标签之后通过<circle>
标签进行渲染。在上面的原始问题中没有提到它,但是我还假设将图像插入圆内可能会解决问题。因此:
<svg height="670" width="670">
<circle cx="350" cy="350" r="300" stroke="black" stroke-width="5" fill="none">
<img src={AnimeCropped} alt={AnimeCropped}/>
</circle>
</svg>
但是这没有用。
在我的最终代码中,您会看到<image>
标记在<circle>
标记之后,因此从技术上讲,它并不是真正地[[inside圆圈,而是叠加在圆圈之上。另请注意,我必须使用<image>
,而不是<img>
。我将对此进行一些研究,但是<img>
给我一个错误消息。
xlink:href
无效,但xlinkHref
可以!这确实使我感到震惊,但我发现这很有帮助post。somewhat