thx / resvg-js

A high-performance SVG renderer and toolkit, powered by Rust based resvg and napi-rs.
https://resvg-js.vercel.app/
Mozilla Public License 2.0
1.58k stars 59 forks source link

[question] using directly an SVGSVGElement created with other code #335

Closed dawadam closed 6 months ago

dawadam commented 6 months ago

Is it possible to directly use an SVGSVGElement created with other code? Otherwise I need to serialize for parsing, not really efficient.

dawadam commented 6 months ago

I found a alternative solution here : https://talk.observablehq.com/t/generate-static-png-or-svg-at-build-time-with-framework/8833/2

"chart" is a SVGSVGElement


// add xmlns attribut
chart.setAttribute("xmlns", "http://www.w3.org/2000/svg");

// create resvg instance (using outerHTML)
const instance = new Resvg(chart.outerHTML)

// png conversion
const pngBuffer = instance.render().asPng();
yisibl commented 6 months ago

Yes, you need to add the xmlns namespace for resvg-js to render.

dawadam commented 6 months ago

Other solution, using XMLSerializer. Reference can be found directly inside SVGSVGElement instance, like this : "chart" is a SVGSVGElement instance.

// xml serializer
const serializer = new chart.ownerDocument.defaultView.XMLSerializer();

// svg string (with xmlns namespace)
const svgString = serializer.serializeToString(chart);

// create resvg instance (using outerHTML)
const instance = new Resvg(svgString)

// png conversion
const pngBuffer = instance.render().asPng();
yisibl commented 6 months ago

Thank you for sharing.