I used this trick to add the computed style of each node to its style attribute, and it works. maybe this can help you.
Update 1: Some browsers do not support the cssText property, so you can use the code below, which is a slightly more cross-browser.
Update 2:. Firefox computes a CSS quotation property that includes some invalid string characters that btoa cannot correctly encode.
let addStyle = function(children) { for (let i = 0; i < children.length; i++) { let child = children[i]; if (child instanceof Element) { let cssText = ''; let computedStyle = window.getComputedStyle(child, null); for (let i = 0; i < computedStyle.length; i++) { let prop = computedStyle[i]; cssText += prop + ':' + computedStyle.getPropertyValue(prop) + ';'; } child.setAttribute('style', cssText); addStyle(child.childNodes); } } } let svg = document.querySelector('svg'); addStyle(svg.childNodes); let xml = new XMLSerializer().serializeToString(svg); let data = "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(xml))); let img = new Image(); img.src = data; document.body.appendChild(img);
circle { fill: red }
<svg width="100" height="100"> <circle cx="50" cy="50" r="40" /> </svg>
source share