我试图通过画布元素(受#34; https://bl.ocks.org/biovisualize/8187844")的启发,在savascript中将svgs转换为png,但我还有问题渲染我链接到的字体。
请参阅小提琴:https://jsfiddle.net/2chtz7rx/1/
HTML:
<link href="https://fonts.googleapis.com/css?family=Creepster:400,400" rel='stylesheet' type='text/css'>
<svg id="svg">
<text style="min-height: 43px; margin: 20px; font-size: 200%; font-family: Creepster; font-weight: 400; font-style: normal" x="50%" y="35" text-anchor="middle">FONT</text>
</svg>
<button id="button">render canvas</button>
<img id="img">
<canvas id="canvas"></canvas>
使用Javascript:
document.getElementById('button').onclick = function() {
var str = new XMLSerializer().serializeToString(document.getElementById('svg'))
var svg = new Blob([str], {type: "image/svg+xml;charset=utf-8"});
var url = self.URL.createObjectURL(svg);
var img = document.getElementById('img');
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
img.onload = function() {
ctx.drawImage(img, 0, 0);
self.URL.revokeObjectURL(url);
};
img.src = url;
}
注意svg如何呈现正常,但是当使用svg的url创建img时,它无法正确呈现字体,并且还原为Times new Roman。
有什么建议吗?谢谢!