我正在使用客户端/ javascript函数将现有的D3-SVG图保存或转换为文件。
我搜索了很多并找到了一些建议,主要是使用canvas.toDataURL()
。
我的页面中没有<canvas>
,而是使用:d3.select("body").append("svg")....
我也尝试将SVG附加到<canvas>
,但没有任何反应。
你能帮我解决这个例外:
Uncaught TypeError: Object #<SVGSVGElement> has no method 'toDataURL'
谢谢
答案 0 :(得分:20)
要在画布中显示svg,首先必须使用解析器/渲染器实用程序(例如http://code.google.com/p/canvg/
)对其进行转换(代码改编自:Convert SVG to image (JPEG, PNG, etc.) in the browser,未经测试)
// 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");
答案 1 :(得分:6)
简单地说,我将这个概念转变为一个小型JavaScript库:https://github.com/krunkosaurus/simg
它只是将任何SVG转换为图像以换出或触发下载。从这里获取的想法:http://techslides.com/save-svg-as-an-image/
答案 2 :(得分:4)
正如@Premasagar在关于这个问题的评论Convert SVG to image (JPEG, PNG, etc.) in the browser
中指出的那样如果borwser支持SVG和canvas,您可以使用此技术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);
}
}
答案 3 :(得分:3)
上面由Mauvis Ledford创建和建议的Simg库非常适合允许下载使用Dimple创建的svg图表。
但我确实需要更改代码的一个方面才能使其正常工作。在toString()原型内部,在forEach循环内(第37行),如果你将“svg.setAttribute(..)”更改为“svg [0] .setAttribute”,它将缓解“setAttribute(..)不是功能“错误。同样地,需要在return语句中进行相同的操作,在svg(第39行)之后追加“[0]”。
我还必须手动编辑toCanvas()原型中的“canvas.width”和“canvas.height”(第48行和第49行)分配,以便使下载的图像更正确(它是以前只是下载图表左上角的静态300x150广场)。