본문 바로가기

프론트엔드/리액트

리액트로 이미지 다운로드(html-to-image)

import { useEffect, useRef } from 'react';
import { Doughnut } from 'react-chartjs-2';

import styled from '@emotion/styled';
import { DashboardData } from '~/interfaces/Dashboard';
import { ArcElement, Chart as ChartJS, Legend, Tooltip } from 'chart.js';
import { toPng } from 'html-to-image';
ChartJS.register(ArcElement, Tooltip, Legend);

interface Props {
  items: DashboardData[];
}

function DonutChart({ items }: Props) {
  const chartRef = useRef(null);

  const handleDownloadClick = () => {
    if (chartRef.current !== null) {
      toPng(chartRef.current).then((dataUrl) => {
        const link = document.createElement('a');
        link.download = 'chart.png';
        link.href = dataUrl;
        link.click();
      });
    }
  };

  useEffect(() => {
    console.log(items);
  }, []);

  const data = {
    labels: items.map((item) => item.name),
    datasets: [
      {
        label: '#count',
        data: items.map((item) => item.count),
        backgroundColor: items.map((item) => item.hex),
        borderWidth: 1,
      },
    ],
  };

  return (
    <>
      <ChartContainer ref={chartRef}>
        <Doughnut data={data} />
      </ChartContainer>
      <Button onClick={handleDownloadClick}>다운로드</Button>
    </>
  );
}

export default DonutChart;

const ChartContainer = styled.div`
  align-item: center;
  width: 500px;
  background-color: white;
  height: 500px;
`;

const Button = styled.button`
  width: 100px;
  height: 45px;
  font-size: 10px;
  border-radius: 10px;
`;

만들어진 도넛차트 이미지를 다운로드하려면..

import html-to-image from 'html-to-image' 가 아니라

import {toPng} from 'html-to-image' 를 해야한다.

html-to-image 라이브러리가 기본 내보내기(default export)를 제공하지 않아서 {topng}로 특정해야 한단다.