I'm trying to export svg to png, and auto-download the png. I was able to generate the svg to png with google fonts (copied it to 'canvas' using JS), and the 'copied version' was ok, but when I download the file, the font goes back to default font.
I tried many ideas I have found on the web, but nothing helped.
Does anyone have an idea?
I'm working with .net, if it matters somehow.
<link href="https://fonts.googleapis.com/css?family=Exo+2" rel="stylesheet">
<script src="http://d3js.org/d3.v3.min.js"></script>
<button>Download SVG</button>
<div></div>
<canvas style="visibility: hidden;" id="canvas"></canvas>
<script>
var canvas = d3.select("div").append("svg")
.attr("font-size", "50px")
.attr("width", 150)
.attr("height", 150)
.attr("font-family", "Exo 2")
var circle = canvas.append("circle")
.attr("cx", 50)
.attr("cy", 50)
.attr("r", 50)
.text("lalala");
var text = canvas.append("text")
.attr("x", 100)
.attr("y", 100)
.attr("fill", "green")
.attr("style", "font-family:'Exo 2';")
.attr("font-size", "20px")
.text("lalala");
var btn = document.querySelector('button');
var svg = document.querySelector('svg');
var text = document.querySelector('text');
var canvas = document.querySelector('canvas');
function triggerDownload(imgURI) {
var evt = new MouseEvent('click', {
view: window,
bubbles: false,
cancelable: true
});
var a = document.createElement('a');
a.setAttribute('download', 'svgImage.png');
a.setAttribute('href', imgURI);
a.setAttribute('target', '_blank');
a.dispatchEvent(evt);
}
btn.addEventListener('click', function () {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var data = (new XMLSerializer()).serializeToString(svg);
var DOMURL = window.URL || window.webkitURL || window;
var img = new Image();
var svgBlob = new Blob([data], { type: 'image/svg+xml;charset=utf-8' });
var url = DOMURL.createObjectURL(svgBlob);
img.onload = function () {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
var imgURI = canvas
.toDataURL('image/png')
.replace('image/png', 'image/octet-stream');
triggerDownload(imgURI);
};
img.src = url;
});
</script>
enter code here