html2canvas 이미지 해상도 개선 방법

sumi-0011·2023년 4월 17일
0

🔥 트러블슈팅

목록 보기
7/12
post-thumbnail

html2canvas 라이브러리를 이용해서 DOM을 이미지로 다운받을 수 있다.
그런데 이 과정에서 이미지의 해상도가 깨지는 문제가 발생한다.

html2canvas 이미지 해상도 개선 방법

이는 이미지의 크기를 더 키우는 방식으로 해결할 수 있다.

html2canvas의 React에서의 사용 방법은

const canvas = await html2canvas(captureArea.current, { scale: 4 });

여기서 포인트는 { scale: 4 }을 통해서 다운받는 이미지의 사이즈를 4배로 키워 출력한 것이다!

이미지 다운하는 custom hook 생성

html2canvas를 이용하여 이미지 다운로드 하는 로직을 분리하기 위해 커스텀 훅을 만들어 사용하였다.

html2canvas 사용 전체 코드

import html2canvas from 'html2canvas';
import { useRef } from 'react';

function useImageDownload() {
  const captureArea = useRef<HTMLDivElement>(null);

  /* 다운로드 버튼 함수 */
  const onImageDownload = async () => {
    if (captureArea.current) {
      const canvas = await html2canvas(captureArea.current, { scale: 4 });
      const element = document.createElement('a');
      element.href = canvas.toDataURL('image/png');
      element.download = '2023_Mandalart.png';
      element.click();
    }
  };

  // 이미지 blob 형태로 가져오기, 이부분은 아직 미완성, 필요할때 완성할 예정
  const getImageBlob = async () => {
    if (captureArea.current) {
      const canvas = await html2canvas(captureArea.current);
      canvas.toBlob((blob) => {
        if (!blob) return;
        const url = URL.createObjectURL(blob);
        return url;
      });
    }
  };

  return {
    captureArea,
    onImageDownload,
    getImageBlob,
  };
}

export default useImageDownload;

개발 환경 : React 18 + html2canvas 라이브러리

해상도 개선 전 vs 후

profile
안녕하세요 😚

0개의 댓글