单击外部按钮时,Apexcharts 将图表下载为图像 (PNG)

问题描述 投票:0回答:2

我有一个简单的反应顶点图表,我需要下载它的图像。 Apex 工具栏可以做到这一点,但我想使用外部按钮调用相同的行为。这是我的代码。 这怎么办?

代码沙盒

import React, { useState } from "react";
import "./styles.css";
import Chart from "react-apexcharts";

export default function App() {
  const [state, setState] = useState({
    options: {
      chart: {
        id: "LineGraph1",
        zoom: {
          enabled: false
        },
        toolbar: { show: true }
      },
      dataLabels: {
        enabled: false
      },
      xaxis: {
        categories: [1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999]
      }
    },
    series: [
      {
        name: "series-1",
        data: [30, 40, 45, 50, 49, 60, 70, 91]
      }
    ]
  });

  async function downloadSVG(chartId) {
    console.log(window.Apex._chartInstances);
    const chartInstance = window.Apex._chartInstances.find(
      (chart) => chart.id === chartId
    );
    console.log("chartInstance ", chartInstance);
    const base64 = await chartInstance.chart.dataURI();
    console.log("base 64", base64);
    // chartInstance.dataURI().then(({ imgURI, blob }) => {
    //   console.log("URI ", imgURI, " ", blob);
    // });
    const blob = await (await fetch(base64)).blob();
    const x = await fetch(base64)
      .then((res) => res.blob())
      .then((blob) => console.log(blob))
      .catch((err) => console.log(err));
    return blob;
  }

  return (
    <div className="App">
      <Chart
        options={state.options}
        series={state.series}
        type="area"
        height="280"
      />
      <button onClick={() => downloadSVG("LineGraph1")}>Download svg</button>
    </div>
  );
}
javascript reactjs charts apexcharts react-apexcharts
2个回答
1
投票
  async function downloadSVG(chartId) {
    console.log(window.Apex._chartInstances);
    const chartInstance = window.Apex._chartInstances.find(
      (chart) => chart.id === chartId
    );
    console.log("chartInstance ", chartInstance);
    const base64 = await chartInstance.chart.dataURI();
    console.log("base 64", base64.imgURI);
    const downloadLink = document.createElement("a");
    downloadLink.href = base64.imgURI;
    downloadLink.download = "image.png";

    // Add the anchor element to the document
    document.body.appendChild(downloadLink);

    // Simulate a click event to initiate the download
    downloadLink.click();

    // Remove the anchor element from the document
    document.body.removeChild(downloadLink);
  }

这已经在您的沙箱中进行了测试和工作。


0
投票

使用内部方法的更短解决方案:

const downloadPNG = (chartId) => {
    const chartInstance = ApexCharts.getChartByID(chartId);

    if (!chartInstance) {
        return;
    }

    chartInstance.exports.exportToPng();
}
© www.soinside.com 2019 - 2024. All rights reserved.