You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过外部按钮触发ApexCharts图表的PNG图片下载

实现React ApexCharts外部按钮触发图表下载

你需要通过外部按钮触发ApexCharts图表的下载功能,替代自带工具栏的下载操作,以下是修正后的实现方案:

核心逻辑说明

  1. 通过window.Apex._chartInstances查找对应ID的图表实例
  2. 调用实例的dataURI()方法获取图表的图片资源(支持PNG/SVG格式)
  3. 创建临时下载链接,触发浏览器的下载行为

完整代码实现

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 } // 若不需要自带工具栏,可设置为false隐藏
      },
      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 downloadChart(chartId) {
    // 匹配目标图表实例
    const chartInstance = window.Apex._chartInstances.find(
      (chart) => chart.id === chartId
    );

    if (!chartInstance) {
      console.error(`未找到ID为${chartId}的图表实例`);
      return;
    }

    // 获取图表的base64格式图片链接
    const { imgURI } = await chartInstance.chart.dataURI();
    
    // 创建临时下载链接并触发下载
    const downloadLink = document.createElement('a');
    downloadLink.href = imgURI;
    downloadLink.download = `${chartId}.png`; // 设置下载文件名
    downloadLink.click();
    // 下载完成后移除临时元素
    downloadLink.remove();
  }

  return (
    <div className="App">
      <Chart
        options={state.options}
        series={state.series}
        type="area"
        height="280"
      />
      <button onClick={() => downloadChart("LineGraph1")}>下载图表</button>
    </div>
  );
}

扩展:下载SVG格式图表

如果需要下载SVG格式的图表,只需在dataURI()方法中传入格式配置:

const { imgURI } = await chartInstance.chart.dataURI({
  format: 'svg'
});
downloadLink.download = `${chartId}.svg`;

内容的提问来源于stack exchange,提问作者Sanath

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 07:12:05