简体   繁体   中英

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

I created an html page for my tool which works offline(client side). 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. These two image download button works fine, when tested separately in two different html pages.

Now, Problem in combined html page, is that each button is downloading the image of first d3 based graph only.

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.

**I think there is problem while calling "node( ).parentNode.innerHTML;" (mentioned in following svg downlaod script)? But I don't know how to call different SVG in this script. This is my first time, I am working on 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.

Instead of that, give your SVGs unique IDs (like svg1 and svg2 ), and select by those IDs:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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