'Javascript: How can i choose which chart will be downloaded to png

I'm working on a website that displays different spectrums. I display them as charts using ChartJS. Right now i'm displaying two different types of spectrums.

I can switch from one to another with those two buttons:

<div class="w-full flex flex-row">
                <button class="w-1/2 py-1 bg-green-600 text-xl text-gray-100 font-medium transition-colors hover:text-gray-900 focus:outline-none"
                        id="button-spectrum"
                        type="button">
                    Spectrum
                </button>
                <button class="w-1/2 py-1 bg-gray-100 text-xl font-medium transition-colors hover:text-green-600 focus:outline-none"
                        id="button-normalized-spectrum"
                        type="button">
                    Normalized spectrum
                </button>
            </div> 

Then i use a button that downloads a spectrum to png.

document.getElementById("button-save-png").addEventListener("click", function () {
      let image;
      setTimeout(function () {
          image = normalized_chart.toBase64Image("image/png", 1);
          image = chart.toBase64Image("image/png", 1);
          let link = document.createElement("a");
          let date = new Date();
          // define the name of the download PNG
          link.download = spec_name + "-graph-" + ("00" + (date.getMonth() + 1)).slice(-2) + "_" +
              ("00" + date.getDate()).slice(-2) + "_" +
              date.getFullYear() + "-" +
              ("00" + date.getHours()).slice(-2) + "_" +
              ("00" + date.getMinutes()).slice(-2) + "_" +
              ("00" + date.getSeconds()).slice(-2) + ".png";
          link.href = image;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
      }, 1000);
  });

But right now, i can only download the first kind of spectrum. How can i make it that i can choose which spectrum i want to download, and then download it.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source