简体   繁体   English

在单个 html 页面中下载两个不同 d3 图形的图像?

[英]downloading images of two different d3 graphs in single html page?

I created an html page for my tool which works offline(client side).我为我的工具创建了一个 html 页面,该页面可离线工作(客户端)。 This page is creating two different d3 based graph and I created two different buttons (save and save1)for each graph to downlaod images of these.此页面正在创建两个不同的基于 d3 的图形,我为每个图形创建了两个不同的按钮(保存和保存 1)以下载这些图像。 These two image download button works fine, when tested separately in two different html pages.当在两个不同的 html 页面中分别测试时,这两个图像下载按钮工作正常。

Now, Problem in combined html page, is that each button is downloading the image of first d3 based graph only.现在,组合 html 页面中的问题是每个按钮仅下载第一个基于 d3 的图形的图像。

I defined two different svg variable (svg and svg1) for each graph creation but i donot know how to call it differently in downloadimage script.我为每个图形创建定义了两个不同的 svg 变量(svg 和 svg1),但我不知道如何在 downloadimage 脚本中以不同的方式调用它。

**I think there is problem while calling "node( ).parentNode.innerHTML;" **我认为调用“node().parentNode.innerHTML;”时有问题(mentioned in following svg downlaod script)? (在以下 svg 下载脚本中提到)? But I don't know how to call different SVG in this script.但我不知道如何在这个脚本中调用不同的 SVG。 This is my first time, I am working on d3.这是我第一次,我正在研究 d3。 ** **

d3.select("#save1").on("click", function(){  //button save in first graph;
  var html1 = d3.select("svg")           //var html in first graph;
    .attr("version", 1.1)
    .attr("xmlns", "http://www.w3.org/2000/svg")
    .node( ).parentNode.innerHTML;   
    //console.log(html);

  var imgsrc = 'data:image/svg+xml;base64,'+ btoa(html1);
  var image = new Image;
    image.src = imgsrc;

image.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext('2d');
context.fillStyle = "#FFFFFF";
context.fillRect(0,0,image.width,image.height);
context.drawImage(image, 0, 0);

var a = document.createElement('a');
a.download = "image.png";
a.href = canvas.toDataURL('image/png');
document.body.appendChild(a);
 a.click();
}
}); 

This line:这一行:

 var html1 = d3.select("svg")

Is always selecting the first SVG in the DOM, regardless the button you click.无论您单击哪个按钮,始终选择 DOM 中的第一个 SVG。

Instead of that, give your SVGs unique IDs (like svg1 and svg2 ), and select by those IDs:取而代之的是,为您的svg1提供唯一 ID(如svg1svg2 ),并通过这些 ID 进行选择:

 var html1 = d3.select("#svg1")

 var html2 = d3.select("#svg2")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM