SVG for PNG with built-in list of styles

I am interested in creating PNG from SVG. I have executed the code indicated in:

https://developer.mozilla.org/en-US/docs/HTML/Canvas/Drawing_DOM_objects_into_a_canvas

But the image fails due to the style of CSS. I created a local CSS file and imported it into SVG, as described in:

How to apply style to embedded SVG?

But it does not seem to use a stylesheet. Any ideas why I would have this error?

Thanks.

+4
source share
3 answers

Take a look at PhantomJS - you need to install it, either write your own script, or run something in these lines:

phantomjs rasterize.js http://ariya.github.com/svg/tiger.svg tiger.png 

You can also save to PDF, set the zoom setting, etc.

0
source

You can use html2canvas to create a canvas from any dom element (including svg elements).

However, the style definitions for svg elements defined in style sheets do not apply to the generated canvas. This can be fixed by adding style definitions to svg elements before calling html2canvas.

Inspired by this article , I created this:

 function generateStyleDefs(svgDomElement) { var styleDefs = ""; var sheets = document.styleSheets; for (var i = 0; i < sheets.length; i++) { var rules = sheets[i].cssRules; for (var j = 0; j < rules.length; j++) { var rule = rules[j]; if (rule.style) { var selectorText = rule.selectorText; var elems = svgDomElement.querySelectorAll(selectorText); if (elems.length) { styleDefs += selectorText + " { " + rule.style.cssText + " }\n"; } } } } var s = document.createElement('style'); s.setAttribute('type', 'text/css'); s.innerHTML = "<![CDATA[\n" + styleDefs + "\n]]>"; //somehow cdata section doesn't always work; you could use this instead: //s.innerHTML = styleDefs; var defs = document.createElement('defs'); defs.appendChild(s); svgDomElement.insertBefore(defs, svgDomElement.firstChild); } // generate style definitions on the svg element(s) generateStyleDefs(document.getElementById('svgElementId')); // after generating the style defintions, call html2canvas html2canvas(document.getElementById('idOfElement')).then(function(canvas) { document.body.appendChild(canvas); }); 
0
source

Example in

"How to apply style to embedded SVG?" as you mentioned, should work. You need to define youObjectElement in this line of code when you test it.

var svgDoc = yourObjectElement.contentDocument;

Try again.

-1
source

All Articles