haedaal
11/8/2016 - 9:53 AM

svg2png, svg, canvas, png, serialize, xml, image, dynamic, base64

svg2png, svg, canvas, png, serialize, xml, image, dynamic, base64

function svg2Png(svg, imgHolder, width, height) {
		var canvas = document.createElement("canvas");
    var context = canvas.getContext("2d");

    // to tackle blurring issue, draw on large canvas and down scale
    var image = new Image();
		image.width = canvas.width = width * 2;
		image.height = canvas.height = height * 2;

    var svgAsXML = (new XMLSerializer()).serializeToString(svg);
		var index = svgAsXML.match(/<svg.*?>/)[0].length;

    var style = '<defs xmlns="http://www.w3.org/1999/xhtml"><style type="text/css"><![CDATA[svg text {font: 10px sans-serif; text-anchor: middle; } .bar-top {font-weight:bold; } .bold {font-weight:bold; } .first-bar {fill: skyblue; } .second-bar {fill: rgb(252,199,76); } .axis text {font: 10px sans-serif; } .axis.x line {display:none; } .axis path, .axis line {fill: none; stroke: #000; shape-rendering: crispEdges; } tspan {font-size:10pt; } .title {font-size:13pt !important; } .total-count-legend {text-anchor: end !important; font-size:11pt; } .yGrid {stroke:gray !important; stroke-dasharray: 5 5; }]]></style></defs>';

		svgAsXML = svgAsXML.slice(0, index) + style + svgAsXML.slice(index);

		image.src = 'data:image/svg+xml,' + encodeURIComponent( svgAsXML );	
		image.onload = function() {
			console.log("loaded");
     context.drawImage(image, 0, 0, canvas.width, canvas.height);

      imgHolder.src = canvas.toDataURL("image/png");
      imgHolder.width = width;
      imgHolder.height = height;
		};
}