简体   繁体   中英

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. The svg file has a color in it that I want to change to my own color (which is not known ahead of time). I realize getSourceCode and setSourceCode are not real methods but I used them to hopefully demonstrate what I am trying to accomplish.

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

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.

Now you can modify all SVG props with react. for example, an SVG code can have multi fill prop that you can get it from the prop.

Demo

编辑 mystifying-water-8orxh

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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