Search code examples
javascriptnode.jsimage-processingvector-graphics

How can you dynamically import, modify, and export vector files?


I want to be able to import SVG files from the file system, layer them, change their fill colors, and then export them as a single vector file.


Solution

  • The solution to this problem was simply to import the SVG data as a string, swap out constants for various properties, and then write the new string to the file system.

    For example, the following svg displays an orange circle:

    <svg viewBox="0 0 1000 1000" xmlns="http://www.w3.org/2000/svg">
      <circle cx="500" cy="500" r="500" fill="orange"/>
    </svg>
    

    If you wanted to be able to dynamically change the color of the circle, you could just replace the "orange" text with a placeholder name, such as "{FILL_COLOR}". Now, the SVG should look like this:

    <svg viewBox="0 0 1000 1000" xmlns="http://www.w3.org/2000/svg">
      <circle cx="500" cy="500" r="500" fill="{FILL_COLOR}"/>
    </svg>
    

    In your code, you can load the file from the file system as a string and then make changes to it as needed; you could then write the result to the file system. This solution also works perfectly on frontends. Instead of loading the SVG from the file system, simply have it as a hard-coded constant. Once you make the changes to the SVG, you can use the result however you want.

    function getCircle(color) {
      const svg = `<svg viewBox="0 0 1000 1000" xmlns="http://www.w3.org/2000/svg"><circle cx="500" cy="500" r="500" fill="{FILL_COLOR}"/></svg>`;
      return svg.replace('{FILL_COLOR}', color);
    }