Using css in converted svg to img

I am trying to convert SVG to image format. Actually works a lot very well, and I know how to convert from SVG to canvas and from canvas to img. My problem is that svg uses css, which was included as a css file and by converting to canvas the styles will be lost.

Does anyone have an idea how to copy styles into my SVG or canvas?

Here is my code: https://jsfiddle.net/DaWa/70w9db1d/

<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>SVG2IMG</title> <link rel="stylesheet" href="./circle.css"> </head> <body> <svg width="100" height="100"> <circle cx="50" cy="50" r="40"/> </svg> <script> var svg = document.querySelector('svg'); let xml = new XMLSerializer().serializeToString(svg); let data = "data:image/svg+xml;base64," + btoa(xml); let img = new Image(); img.src = data; document.body.appendChild(img) </script> </body> </html> 

And my css:

 circle { fill:red } 
+5
source share
1 answer

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> 
+3
source

Source: https://habr.com/ru/post/1269591/


All Articles