2018年11月2日 星期五

[Javascript] 用Javascirpt截圖的小幫手 html2canvas


請先到html2canvas的官網下載套件
https://html2canvas.hertzen.com/

在想要擷取的畫面加上一個id方便來獲取這個元件,這邊設成capture。
<div id="capture"> ... </div>

這時候就可以擷取儲存成canvas,這邊是直接將這個畫面加到網頁的結尾。
html2canvas(document.querySelector("#capture")).then(canvas => {
    // do something
    document.body.appendChild(canvas)
});
querySelector這邊請記得針對你要擷取的元件設定!

完整的範例如下:
<html>
 <head>
<html>
 <head>
  <title>Screenshots with JavaScript</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" >
 </head>

 <body>
  <div class="container">
   <div class="row">
    <div class="col my-5">
     <!-- The Screenshot Component -->
     <div class="target">
      <div class="card text-center">
       <div class="card-header">
        Featured
       </div>
       <div class="card-body">
        <h5 class="card-title">Special title treatment</h5>
        <p class="card-text">With supporting text below as a natural lead-in to additiona    l content.</p>
        <a href="#" class="btn btn-primary">Go somewhere</a>
       </div>
       <div class="card-footer text-muted">
        2 days ago
       </div>
      </div>
     </div>

     <!-- Display Area -->
     <div class="mt-5 result border border-success">
      <p class="text-center">Display Here!</p>
     </div>

     <!-- Download Link -->
     <a herf="#" class="download-link btn">Download</a>
    </div>
   </div>
  </div>
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
  <script type="text/javascript" src="./html2canvas.min.js"></script>
  <script>
  $(document).ready(function() {
   html2canvas(document.querySelector(".target")).then(canvas => {
     $(".result").append(canvas);
     $(".download-link").attr("href", canvas.toDataURL());
   });
  });
  </script>
 </body>

</html>

沒有留言:

張貼留言