将D3图表另存为图像 [英] Save D3 chart as image

查看:556
本文介绍了将D3图表另存为图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用程序中创建了许多D3图表.

I created lots of D3 chart in the application .

但是现在我的要求是将D3图表保存为png/gif或pdf等任何格式.

But right now my requirement is to save D3 chart in any format like png/gif or pdf.

我搜了很多东西,每个人都说我们可以用帆布做这件事.

I searched a lot and every one say we can use canvas for that.

任何人都可以为此提供任何示例或链接...

Can anyone give any example or link for that...

从概念上讲,我很清楚

使用canvg JavaScript库通过Canvas渲染SVG图像: https://github.com/gabelerner/canvg

Use the canvg JavaScript library to render the SVG image using Canvas: https://github.com/gabelerner/canvg

根据以下说明,从Canvas中捕获编码为JPG(或PNG)的数据URI:将HTML Canvas捕获为gif/jpg/png/pdf?

Capture a data URI encoded as a JPG (or PNG) from the Canvas, according to these instructions: Capture HTML Canvas as gif/jpg/png/pdf?

如果有任何实现,我实际上想要的是什么,那么请您分享代码.

What I want actually if any one have implemented, then could you please share the code.

推荐答案

在搜索了许多资源并尝试了许多方法之后,我发现了 SaveSvgAsPng 在GitHub上.

After searching many resources and trying many things, I found SaveSvgAsPng on GitHub.

使用同一链接的README页面上的可用资源非常容易实现和使用.

It's very easy to implement and to use with resources available on README page on the same link.

步骤

  1. 将Javascript库添加到您的项目中.
  2. 编写带有saveSvgAsPng调用的函数,并根据需要包括其他选项.

用法示例

saveSvgAsPng(document.getElementsByTagName("svg")[0], "plot.png");

使用d3.js的示例功能

// I have button in html with id="download"
d3.select("#download")
.on('click', function(){
    // Get the d3js SVG element and save using saveSvgAsPng.js
    saveSvgAsPng(document.getElementsByTagName("svg")[0], "plot.png", {scale: 2, backgroundColor: "#FFFFFF"});
})

在此示例中,我的图对于一个网页来说很小,因此将其大小增加了一倍以进行下载,而不是将透明背景设置为默认值(默认情况下,我改为白色).

For this example, my plots are small for a web page so increased size to double for download and rather than transparent background as default I changed to white.

这篇关于将D3图表另存为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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