我试图将svg导出到png,并自动下载png。 我能够用google字体生成svg到png(将它复制到' canvas'使用JS),以及复制版本'没关系,但是当我下载文件时,字体会恢复为默认字体。
我尝试了很多我在网上找到的想法,但没有任何帮助。
有人有想法吗?
我和.net合作,如果它以某种方式重要。
<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>
在这里输入代码