首页 > 解决方案 > React JSX - 用图像填充 svg

问题描述

我正在尝试用 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;

我的第一个直觉是通过用orfill替换原始颜色来调整属性,但两者都不起作用。="red"={Anime}=url("../images/Anime.jpeg")

(我知道动漫图像的路径是正确的,在通过<img src={Anime} alt={Anime}></img>在 div 中渲染进行测试之后。

我看到人们使用<defs><pattern>标签,例如(参考这篇文章):

<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 中,周围有一个厚厚的黑色边框。

在此处输入图像描述

标签: reactjssvgjsxfill

解决方案


我想出了一种方法并想发布/分享它,以防有人在这里,看着这篇文章并想知道(其中一个)解决方案是什么!

这是我的最终代码:

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;

基本上我所做的是:

  1. 将照片裁剪为圆形。我本可以按照上面cubrr的建议并对其进行剪辑路径(这是一个好主意!),但相反 - 我只是在网上找到并使用了一个照片裁剪工具。然后我将新裁剪的图片命名为“AnimeCropped”并将其保存在同一目录中。

  2. 将图片导入到组件文件中,并通过<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>标签之后,所以从技术上讲,它并不是真正圆圈内,而只是覆盖在圆圈之上。另请注意,我必须使用<image>,而不是<img>. 我将不得不对此进行一些研究,但是<img>给了我一条错误消息。

同样重要的是:在 React 中,xlink:href不会工作,但xlinkHref会!这真的让我大吃一惊,但我发现这个有用的帖子

  1. 使用 classNames,我在 App.css 文件中编辑了裁剪图片的大小。

  2. 配置 x 和 y 坐标,使其在某种程度上完全适合圆的中间。

而已!只是想发布这个以结束/帮助我回顾我学到的东西。


推荐阅读