I am trying to convert svg to png and I found that the converted image is not the same as svg. How can as assure consistency among both svg and png?
Code to covert svg to png
jQuery('#imgDiv').css({display: 'block', 'padding-left': '25px', overflow: 'scroll'});
jQuery('#resImg').css({display: 'block', 'padding-left': '25px'});
var svg = jQuery('#map').html().replace(/>\s+/g, ">").replace(/\s+</g, "<");
// strips off all spaces between tags
canvg('cvs', svg, {
ignoreMouse: true,
ignoreAnimation: true
});
var canvas = document.getElementById('cvs');
img = canvas.toDataURL("image/png", 1);
var a = document.createElement('a');
a.href = img;
a.download = "image.png";
var clickEvent = new MouseEvent("click", {
"view": window,
"bubbles": true,
"cancelable": false
});
a.dispatchEvent(clickEvent)
Everything is file but when I see the downloaded image the height,width is different and labels and fonts is not visible.
Code to generate svg:
var width = 1260,
height = 910;
var svg = d3.select("#map")
.append("svg")
.attr("width", width)
.attr("height", height)
.on("contextmenu", function (d, i) {
d3.event.preventDefault();
printMap();
});
svg.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", width)
.attr("height", height)
.style("stroke", '#000000')
.style("stroke-opacity", 1)
.style("fill", "#FFF")
.style("fill-opacity", 0)
.style("stroke-width", 2);
var cluster = topojson.feature(data, data.objects.clustergeojson).features;
var projection = d3.geo.mercator();
s = 250;
projection.scale(8500)
.center([83, 29.5]);
var path = d3.geo.path().projection(projection);
var b = path.bounds(cluster),
s = .95 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0][1]) / height),
t = [(width - s * (b[1][0] + b[0][0])) / 2, (height - s * (b[1][1] + b[0][1])) / 2];
Actual SVG:
Converted PNG:
Here is sample jsFiddle.
var projection = d3.geo.mercator()
.scale(5000)
.center([83.96, 28.27]);
If I change scale from 5000 to 6000 the svg is larger but not the png. The fiddle output svg can be right clicked to export as png.
Here is the fiddle I have played around with : https://jsfiddle.net/thatoneguy/bnLoq1Lw/9/
I have adjusted yours so you dont have to scroll to see the whole svg. Also added:
instead of right clicking, just a left click event.
on click, save to file but also save to an output
div so you can see the output on screen straight away.
added inline styling so the styling comes out on the generated output.
Inline styling :
.style('stroke','red')
.style('fill','green')
Now when you change the scale, it all seems to work fine ? Where as before I couldn't even see anything.
Have a look at the fiddle I have shown, let me know if it works okay for you