简体   繁体   English

如何使用 javascript 动态替换 .svg 文件的一部分?

[英]How can I dynamically replace parts of a .svg file using javascript?

I am importing a svg file to use as an image in my project.我正在导入一个 svg 文件以在我的项目中用作图像。 The svg file has a color in it that I want to change to my own color (which is not known ahead of time). svg 文件中有一种颜色,我想将其更改为我自己的颜色(提前未知)。 I realize getSourceCode and setSourceCode are not real methods but I used them to hopefully demonstrate what I am trying to accomplish.我意识到 getSourceCode 和 setSourceCode 不是真正的方法,但我用它们来展示我想要完成的事情。

import React from "react";
import emptyOrderImage from "./images/illustrations/empty_order.svg";

function CurrentOrder(props) {
  // Trying to get svg source code as string
  let svgSourceCodeString = emptyOrderImage.getSourceCode();

  // Assume the new color was dynamically loaded
  const newColor = "#FAFAFA";

  // I am trying to replace all occurences of #FFA500 with the new color
  const newSourceCode = originalSourceCode.replace(/#FFA500/gi, newColor);

  // Now I need to set svg to new source code
  emptyOrderImage.setSourceCode(newSourceCode);

  return (
    <div style={{ flex: "display", justifyContent: "center" }}>
      <img src={emptyOrderImage} style={{ width: 200, height: 200 }} />
    </div>
  );
}

export default CurrentOrder;

You can create svg.js file in your project and insert all your SVG files with jsx format code like below:您可以在您的项目中创建svg.js文件,并使用 jsx 格式代码插入所有 SVG 文件,如下所示:

// svg.js

export const HomeSvgIcon = () => {/* svg code */}

export const MenuSvgIcon = () => {/* svg code */}

You should just get the SVG code of each SVG and put in this site and get jsx format of your SVG code.您应该只获取每个 SVG 的 SVG 代码并将其放入此站点并获取 SVG 代码的 jsx 格式。

Now you can modify all SVG props with react.现在您可以使用 react 修改所有 SVG 道具。 for example, an SVG code can have multi fill prop that you can get it from the prop.例如,一个 SVG 代码可以有多重fill道具,你可以从道具中获取它。

Demo演示

编辑 mystifying-water-8orxh

如果您按照@MohammadReza Khedri 的建议将 SVG 渲染到 DOM 中,则可以使用 CSS 变量设置 SVG 的样式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM