Moe*_*ein 30 svg pdf-generation d3.js
我正在使用客户端/ javascript函数将现有的D3-SVG图保存或转换为文件.我经常搜索并找到一些建议,主要是使用canvas.toDataURL().
我没有<canvas>在我的页面中,而是使用:d3.select("body").append("svg")....
我也尝试将SVG附加到<canvas>但没有任何反应.
你能帮我解决这个例外:
Uncaught TypeError: Object #<SVGSVGElement> has no method 'toDataURL'
Run Code Online (Sandbox Code Playgroud)
谢谢
wid*_*ged 20
要在画布中显示svg,首先必须使用解析器/渲染器实用程序(例如http://code.google.com/p/canvg/)对其进行转换.
(代码改编自:在浏览器中将SVG转换为图像(JPEG,PNG等),未经测试)
// the canvg call that takes the svg xml and converts it to a canvas
canvg('canvas', $("#my-svg").html());
// the canvas calls to output a png
var canvas = document.getElementById("canvas");
var img = canvas.toDataURL("image/png");
Run Code Online (Sandbox Code Playgroud)
我把这个概念变成了一个小型的JavaScript库:https://github.com/krunkosaurus/simg
它只是将任何SVG转换为图像以换出或触发下载.从这里获取的想法:http://techslides.com/save-svg-as-an-image/
正如@Premasagar 在这个问题的评论中指出的那样Convert SVG to image (JPEG, PNG, etc) in the browser
如果浏览器同时支持 SVG 和画布,您可以使用此技术https://svgopen.org/2010/papers/62-From_SVG_to_Canvas_and_Back/index.html
function importSVG(sourceSVG, targetCanvas) {
// https://developer.mozilla.org/en/XMLSerializer
svg_xml = (new XMLSerializer()).serializeToString(sourceSVG);
var ctx = targetCanvas.getContext('2d');
// this is just a JavaScript (HTML) image
var img = new Image();
// http://en.wikipedia.org/wiki/SVG#Native_support
// https://developer.mozilla.org/en/DOM/window.btoa
img.src = "data:image/svg+xml;base64," + btoa(svg_xml);
img.onload = function() {
// after this, Canvas’ origin-clean is DIRTY
ctx.drawImage(img, 0, 0);
}
}
Run Code Online (Sandbox Code Playgroud)