Thanks to visit codestin.com
Credit goes to Github.com

Skip to content

Merging multiple SVG files into a single one, with layer processing.

License

Notifications You must be signed in to change notification settings

Zes-MinKey-Young/zsvg

Repository files navigation

zsvg

Merge multiple SVG files into one, with layers (the z attribute).

The project is made possible by:

Why ZSVG?

If you use multiple SVG files in a SVG file directly, all the parts of the latter files will be rendered above the former ones, but we may actually want to use an interleaving order. ZSVG provides a way to solve this problem.

Example

If we have a file a.z.svg containing:

<svg width="100" height="100" viewBox="0 0 100 100">
    <g z="1"><circle cx="0" cy="0" r="10"/></g>
    <g z="2"><circle cx="3" cy="0" r="10"/></g>
</svg>

and another file b.z.svg containing:

<svg width="100" height="100" viewBox="0 0 100 100">
    <g import="a.z.svg" transform="translate(10, 10)"></g>
    <g import="a.z.svg" transform="translate(-10, 10)"></g>
    <g z="1"><circle cx="3" cy="3" r="10"/></g><!-- 与被导入的文件中的层1一起添加到层1中 -->
</svg>

zsvg a.z.svg gives the output:

<svg width="100" height="100" viewBox="0 0 100 100">
    <g z="1">
        <circle cx="3" cy="3" r="10"/>
        <g transform="translate(10, 10)">
            <circle cx="0" cy="0" r="10"/>
        </g>
        <g transform="translate(-10, -10)">
            <circle cx="0" cy="0" r="10"/>
        </g>
    </g>
    <g z="2">
        <g transform="translate(10, 10)">
            <circle cx="3" cy="0" r="10"/>
        </g>
        <g transform="translate(-10, -10)">
            <circle cx="3" cy="0" r="10"/>
        </g>
    </g>
</svg>

Usage

Install: npm install zsvg -g.

Run: zsvg [zsvg] <file.svg> [-o <out.svg>] [-w [callback]]. (zsvg works the same as zsvg zsvg.)

Options:
  -o, --out <filename>          Specify output file (Defaults to [name].o.svg if the source file ends with '.z.svg' or '.zsvg.xml', otherwise <stdout>.)
  -w, --watch [callbackmodule]  Watch files for changes (recursive).
                                Optionally specify a module to import and call after each processing.
                                There is a debounce of 500ms, only the first change will be processed,
                                changes in the subsequent 500ms will be ignored. (default: false)
  -v, --verbose                 Verbose output
  -h, --help                    Display this message

Run zsvg init <filename> to create an empty SVG file.

Constraints and Specifications

  • The <svg> tag must be the root element.
  • <g> with z attribute must be the child element of <svg>. They can have other attributes that will be inherited.
  • <g import> can have a positioning attribute, being one of no-change (default) and view-box (the <g> will be applied transform according to the viewBox of the imported file). Other attributes of <g import> will be inherited by the imported files.

Practices

Naming

Compared to .z.svg, it is more recommended to name your ZSVG source file with .zsvg.xml extension so that your IDE knows that it is not for viewing, and it will not open it as an image.

Watch mode

Use --watch, and split editor in your VSCode. Put the source file in the left side, and the output file in the right side, so that you can see the changes in real time.

Since 0.4.0, you can also use --watch [callback] to run a callback after each processing. The callback is a relative path to a module that default-exports a function callback(inputFile: string, outputFile: string, outputContent: string | undefined). Note that the output file is not written to disk if the callback is specified. Also, the outputContent can be undefined if an error occurs during processing.

An example of callback:

// optimize.mjs
import { optimize } from "svgo";
import fs from "fs";

function displaySize(bytes) {
    const kb = bytes / 1024;
    if (kb < 0.8) {
        return `${bytes} bytes`;
    } else {
        return `${kb.toFixed(2)} KiB`;
    }
}


export default function (_filePath, outPath, outputContent) {
    if (!outputContent) { // outputContent is undefined if the previous step failed
        return;
    }
    console.log("Optimizing...");
    const optimized = optimize(outputContent, {
        plugins: [
            "mergeStyles",
            "minifyStyles",
            "removeHiddenElems",
            "removeEmptyContainers"
        ]
    }).data;
    console.log(`Optimized size: ${displaySize(Buffer.byteLength(optimized))}.`);
    console.log(`Writing to ${outPath}...`);
    fs.writeFileSync(
        outPath,
        optimized,
        "utf-8"
    )
}

Put the above code in the same directory as your ZSVG file, and run zsvg myfile.zsvg.xml -w optimize.mjs. The optimization will be performed after each change.

If your ZSVG file is large, it is not recommended to use optimization on each change. You can optimize manually when you have finished editing and want to publish your image.

Conditional rendering

Inside the imported file, you can add stylesheets to make some elements (in)visible only when in a certain class. Then you can use <g import="..." class="..."> to control the visibility of parts of the imported file.

Use the callback script above to remove those elements that have display: none.

Current Limitations

  • You can only use <g> and <style> as children of <svg>.
  • Style rules in different <style> tags are directly concatenated. Deduplication of style rules is not supported yet. (However, you can use SVGO in the watcher callback to optimize the output.)

In the future, we may also provide a way to use ZSVG files as templates that you can reuse with parameters.

License

ZSVG is licensed under the MIT license.

Contributions

This is not a big project, and from many aspects, the development is not very mature and not particularly standardized. If you have any suggestions, please feel free to open an issue or pull request.

About

Merging multiple SVG files into a single one, with layer processing.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published