ApexCharts에 기본적으로 차트 이미지 다운로드 버튼이 있는데 별도 버튼으로 분리하려고 한다.
ApexChart 설치하기
공식 홈페이지 : https://apexcharts.com/docs/installation/
Installation & Getting Started – ApexCharts.js
Integrating ApexCharts is as simple as it can get with extensive API docs and 100+ samples ready to be used. Check out all the options of ApexCharts
www.apexcharts.com
apexcharts와 react-apexcharts를 설치해준다.
npm install apexcharts react-apexcharts
설치 후 아래와 같이 import 하여 사용 했다.
import ApexCharts from "apexcharts";
import ReactApexChart from "react-apexcharts";
차트 id 설정하기
div 태그에 id 값을 기준으로 다운로드 하려고 했으나 작동하지 않아 차트 옵션의 chart 부분에 id값을 설정하는 방법으로 진행해야한다.
options: {
chart: {
id: "my-chart", // 차트 ID를 반드시 설정
height: 350,
type: "line",
zoom: {
enabled: false,
},
},
...
이미지 다운로드 코드
차트 아이디를 전달 받아 ApexCharts에서 id값을 찾아 png로 다운로드 한다.
const downloadPNG = (chartId) => {
const chartInstance = ApexCharts.getChartByID(chartId);
if (!chartInstance) {
return;
}
chartInstance.exports.exportToPng();
};
전체 코드
import ApexCharts from "apexcharts";
import ReactApexChart from "react-apexcharts";
function App() {
const downloadPNG = (chartId) => {
const chartInstance = ApexCharts.getChartByID(chartId);
if (!chartInstance) {
return;
}
chartInstance.exports.exportToPng();
};
const state = {
series: [
{
name: "Desktops",
data: [10, 41, 35, 51, 49, 62, 69, 91, 148],
},
],
options: {
chart: {
id: "my-chart", // 차트 ID를 반드시 설정
height: 350,
type: "line",
zoom: {
enabled: false,
},
},
dataLabels: {
enabled: false,
},
stroke: {
curve: "straight",
},
title: {
text: "Product Trends by Month",
align: "left",
},
grid: {
row: {
colors: ["#f3f3f3", "transparent"], // takes an array which will be repeated on columns
opacity: 0.5,
},
},
xaxis: {
categories: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
],
},
},
};
return (
<>
<ReactApexChart
options={state.options}
series={state.series}
type="line"
height={350}
width={800}
/>
<button
onClick={() => downloadPNG("my-chart")}
style={{ marginTop: "10px" }}
>
차트 이미지 다운로드
</button>
</>
);
}
export default App;
'시각화' 카테고리의 다른 글
[HTML] html 문서 안에 는 무엇인가? - 특수문자 (0) | 2023.04.11 |
---|---|
[deck.gl] 우리나라 지도 만들기 (Arc Layer) (0) | 2023.04.05 |
[Echarts] SVG 게이지 그래프 만들기 (0) | 2023.04.04 |