Input + Output = True

html2canvas 사용법] 자바스크립트 화면 캡처 / 리액트 화면 캡처 본문

🎨FrontEnd

html2canvas 사용법] 자바스크립트 화면 캡처 / 리액트 화면 캡처

IOTrue 2023. 3. 2. 02:20

html2canvas 사용법] 자바스크립트 화면 캡처 / 리액트 화면 캡처

 

이번 프로젝트에서 적용한 화면 캡처 라이브러리 'html2canvas'를 알아보자.

1. 현재 화면 캡처

2. 캡처된 이미지 pc다운로드

 

리액트를 기준으로 작성됨.

 

 

1. html2canvas 설치

// npm
npm install html2canvas

// yarn
yarn add html2canvas

 

2. 적용 코드

import html2canvas from 'html2canvas';

 //캡쳐할 엘리먼트
  const captureBoxRef = useRef()
  
  
  //캡쳐 진행
  const onClickCapture = async () => {
    console.log("캡쳐 시작")
    html2canvas(captureBoxRef.current,{
      //option 적용 영역, 현재 값 없음
    }).then(canvas => {
     console.log("캡쳐 찰칵 : " , canvas)
     onSaveImage(canvas.toDataURL('image/png'), `capture.png`)
    });
  };
  
  //캡쳐 이미지 다운로드
  const onSaveImage = (uri, fileName) => {
    console.log("onSaveImage")
    const link = document.createElement('a')
    link.style.visibility = "hidden"
    document.body.appendChild(link)
    link.href = uri
    link.download = fileName
    link.click()
    document.body.removeChild(link)
  }
  
  return(
  
  	...
    <StCaptureBox ref={captureBoxRef}>
    ...
  
  
  )

 

3.적용 화면

화면 캡처 작동 화면

 

 

 

 

참고

리액트 버전 : https://www.npmjs.com/package/html2canvas

자바스크립트 버전 : https://html2canvas.hertzen.com/

Comments