작성하고 있는 화면을 이미지로 저장하여 관리해야 하는 일이 생겨 구글링을 했는데 html2canvas 라이브러리를 이용하는 경우가 많아 사용해보았습니다.
npm 링크 :
https://www.npmjs.com/package/html2canvas
html2canvas
Screenshots with JavaScript. Latest version: 1.4.1, last published: 8 months ago. Start using html2canvas in your project by running `npm i html2canvas`. There are 1679 other projects in the npm registry using html2canvas.
www.npmjs.com
먼저 html2canvas를 설치합니다.
yarn add html2canvas
함수를 실행하였을 때, html2canvas로 특정 영역을 그릴 수 있습니다.
html2canvas 는 리턴되는것이 Promise 형태이기 때문에 then함수를 써서 성공했을 때의 행동을 이어서 진행할 수 있습니다.
html2canvas(document.body).then(function(canvas) {
document.body.appendChild(canvas);
});
npm 사이트에서는 위와 같은 예시로 사용이 되었고, 저는 이미지로 저장하여 다운로드를 해야 하는 상황이기 때문에, resolve의 함수를 변경했습니다.
testFunction = () =>{
html2canvas(document.getElementById('test')).then(
(canvas) => {
this.onSaveAs(canvas.toDataURL('image/png'), 'test.png');
}
);
}
onSaveAs는 제가 임의로 만들어 낸 함수이고, a 태그를 만들어 해당 태그에 uri 와 저장할 파일의 이름을 받게 해 두었습니다.
canvas에 사용된 toDataURL()을 사용하면 문자열이 반환되는데, 이 문자열은 Canvas에 그려진 내용을 Data URL로 변환한 것이기 때문에 그 자체로 이미지 정보가 됩니다. 따라서 이 문자열을 이미지 객체에 바인딩하거나 다른 이미지로 생성할 수 있게 됩니다.
아래의 문서에서 toDataUrl에 파라미터로 type을 적어두면 해당 확장자에 맞는 URL을 반환해 줄 것 입니다.
default는 'image/png'입니다.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL
HTMLCanvasElement.toDataURL() - Web APIs | MDN
The HTMLCanvasElement.toDataURL() method returns a data URL containing a representation of the image in the format specified by the type parameter.
developer.mozilla.org
onSaveAs함수는 다음과 같습니다.
onSaveAs = (uri, filename) => {
const link = document.createElement('a');
document.body.appendChild(link);
link.href = uri;
link.download = filename;
link.click();
document.body.removeChild(link);
};
a 태그를 만들고, body안에 자식으로 만들어 준 후, 해당 링크를 클릭하게 되어 다운로드를 받게 하고, 링크를 html안에서 사라지게 만들었습니다.
참고 :
[React] 사진, 캡처 이미지를 사용자가 다운로드 받기
하나의 이미지만 다운로드 받기 // download: (클릭하면) 다운 받아지게 되는 이미지 명 // href: 이미지 경로 특정 버튼을 클릭하여 다운로드 받고 싶은 경우에는 useRef 훅을 이용하여 a 태그에 ref를
imnotadevleoper.tistory.com
https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL
HTMLCanvasElement.toDataURL() - Web APIs | MDN
The HTMLCanvasElement.toDataURL() method returns a data URL containing a representation of the image in the format specified by the type parameter.
developer.mozilla.org
'javascript' 카테고리의 다른 글
[Javascript] 버블링과 캡처링 (0) | 2022.07.20 |
---|---|
[Javascript] Base64 인코드, 디코드 하는 방법- atob(), btoa() (0) | 2022.07.16 |
[Javascript] base64로 인코딩 된 문자열을 ArrayBuffer로 디코딩하기(base64 to array buffer) (0) | 2022.07.15 |
[Javascript] Hash(해시) - 해시 테이블(hash table) 구현하기 (0) | 2022.07.04 |
[Javascript] 배열 정렬하기 sort() (0) | 2022.06.27 |
댓글