본문 바로가기
💻CODING/javascript

[js] html 이미지 저장하기 기능 구현 (ft. html2canvas)

by 코딩하는 갓디노 2022. 3. 28.

[js] html 이미지 저장하기 기능 구현 (ft. html2canvas)

 

html 라이브러리를 통해 
이미지 저장하기 기능입니다.

 

html2canvas

  • html을 canvas로 변환하여 캡처된 화면을 이미지 저장해주는 라이브러리 입니다.

https://www.npmjs.com/package/html2canvas

 

html2canvas

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

www.npmjs.com

 

html2canvas 적용 코드

import html2canvas from 'html2canvas';

...

const onSaveToImg = () => { //클릭 이벤트
  const capture = document.querySelector('#capture') //이미지 저장 영역
  html2canvas(capture).then(
    canvas => {
      saveAs(canvas.toDataURL('image/jpg'), '이미지.jpg')
    }
  )
}

const saveAs = (uri, filename) => {
  let link = document.createElement('a')
  if (typeof link.download === 'string') {
    link.href = uri;
    link.download = filename;
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } else {
    window.open(uri)
  }
}

 

html2canvas 문제점

  • 한가지 문제점은 화면상의 캡쳐 이미지이므로 스크롤이 들어간 넓은 영역의 경우 화면이 잘리게 됩니다. 
  • 이를 위해서 css 로 영역을 넓혀줍니다. 

 

수정코드

const onSaveToImg = () => {
  const capture = document.querySelector('#capture')
  capture.style.width = '1000px' //너비 영역 증가
  capture.style.paddingBottom = '20px'
  html2canvas(capture).then(
    canvas => {
      saveAs(canvas.toDataURL('image/jpg'), '식단표.jpg')
    }
  )
  capture.style.width = 'auto' //원점으로
}
반응형

댓글