본문 바로가기
✨ Front-end/자바스크립트(JS)

[JavaScript] 화면 캡쳐 라이브러리(html2canvas)

by 환풍 2023. 6. 7.
728x90

 

https://html2canvas.hertzen.com

 

html2canvas - Screenshots with JavaScript

Try out html2canvas Test out html2canvas by rendering the viewport from the current page. Capture

html2canvas.hertzen.com

 

 

html

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
  <title>title</title>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <!-- 화면 캡쳐 CDN -->
  <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
</head>
<body>
<button id="shot">screen shot</button>
<!-- 캡쳐할 영역 -->
<div id="capture" style="padding: 10px; background: #f5da55">
  <h4 style="color: #000; ">Hello world!</h4>
</div>
<script>
  $(function(){
    $("#shot").on("click"function(){
            // 캡쳐 라이브러리를 통해서 canvas 오브젝트를 받고 이미지 파일로 리턴한다.
      html2canvas(document.querySelector("#capture")).then(canvas => {
                saveAs(canvas.toDataURL('image/png'),"capture-test.png");
            });
    });
    function saveAs(uri, filename) { 
            // 캡쳐된 파일을 이미지 파일로 내보낸다.
      var 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); 
      } 
    }
  });
</script>
</body>
</html>
cs

참고한 소스 코드

 

html,  js

<!-- 화면 캡쳐 CDN -->

 

위 코드 두 줄은 캡처를 하기 위한 라이브러리니 추가해주어야 한다.

 


 

버튼을 생성하여 screen shot 버튼을 누르게 되면,  오른쪽과 같이 사진이 캡처된다.

 

다운로드 된 폴더에 들어가 사진을 눌러보면, capture에 감싼 id 태그 모두 사진 png로 저장되어 있는 것을 확인할 수 있다.

 


 

반응형

댓글