如何将 d3.js 图形转换/保存为 pdf/jpeg [英] How to convert/save d3.js graph to pdf/jpeg

查看:33
本文介绍了如何将 d3.js 图形转换/保存为 pdf/jpeg的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用客户端/javascript 函数来保存现有 D3-SVG 图形或将其转换为文件.搜索了很多,找到了一些推荐,主要是使用canvas.toDataURL().

I'm working on a client-side/javascript function to save or convert an existing D3-SVG graph into a file. I've searched a lot and found some recommendations, mainly using canvas.toDataURL().

我的页面中没有 ,而是使用:d3.select("body").append("svg")....我还尝试将 SVG 附加到 <canvas> 但没有任何反应.

I have no <canvas> in my page, and instead using:d3.select("body").append("svg").... I've also tried to append the SVG to the <canvas> but nothing happens.

你能帮我解决这个异常吗:

Could you please help me to resolve this exception:

Uncaught TypeError: Object #<SVGSVGElement> has no method 'toDataURL' 

谢谢

推荐答案

正如@Premasagar 在对这个问题的评论中所指出的 在浏览器中将SVG转换为图像(JPEG、PNG等)

As pointed out by @Premasagar in this comment on this question 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

If the borwser supports both SVG and canvas you can use this technique 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);
    }
}

这篇关于如何将 d3.js 图形转换/保存为 pdf/jpeg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆