KassyLog

사진 다운로드 기능 본문

react

사진 다운로드 기능

Kassy_kim 2022. 12. 13. 19:58

현재 내가 진행중인 기능 중 이미지로 다운로드 해야하는 화면이 있는데 서버와 통신하지 않고 웹스토리지 상으로 저장된 데이터를 보여주고 있다.

 

나는 라이브러리를 활용하여 컴포넌트 자체를 화면으로 보여주는 기능을 구현하고 싶었다.

 

내가 사용한 라이브러리는 html2canvas이다.

 

html2canvas

Screenshots with JavaScript. Latest version: 1.4.1, last published: a year ago. Start using html2canvas in your project by running `npm i html2canvas`. There are 1777 other projects in the npm registry using html2canvas.

www.npmjs.com

 

사용한 예제 코드는 다음과 같다.

//library
import html2canvas from "html2canvas";


const Index = () = > {

    //download
      const onCapture = () => {
        // html2canvas에서 html에서 캡처를 할 tag를 매개변수로 넣어주면 canvas를 담아 Promise 객체를 반환
        // 캔버스를 이미지 형태로 리턴하여 id가 imageWrapper인 tag를 감싸게 된다.
        html2canvas(document.getElementById("imageWrapper")).then((canvas) => {
          onSaveAs(canvas.toDataURL("image/png"), "파일이름.png");
        });
      };
      // a 태그를 돔에 삽입하고 매개변수인 uri에 canvas를 집어넣어 canvas 자체를 다운로드(캡처)받는다.
      const onSaveAs = (uri, filename) => {
        const link = document.createElement("a");
        document.body.appendChild(link);
        link.href = uri;
        link.download = filename;
        link.click();
        document.body.removeChild(link);
      };

return (
	<div>
		<button onClick={onCapture}> 사진으로 다운받기 </button>
   		<div id='imageWrapper'>
   			//다운로드 하고자 하는 컴포넌트
   		</div>
    	</div>
)

}

'react' 카테고리의 다른 글

리코일  (0) 2023.03.27
리액트 쿼리  (0) 2023.03.27
emotion과 styled-components  (0) 2023.03.26
craco란?  (0) 2022.12.16
Refresh Token  (0) 2022.12.15