如何用 JavaScript 捕獲 div 的螢幕截圖
我們需要捕獲(轉換成圖片)一些標記的佈局,標記規定了我們網站的佈局,然後儲存捕獲到的圖片或對它進行一些操作。因此,我們需要設計一種方式來實現所描述的行為。
由於我們的問題包括捕獲標記元素,而不僅僅是畫布,因此會有一點複雜,尤其是如果我們計劃從頭開始。因此,為了簡化,我們將使用一個第三方庫 htmltocanvas ,它的作用就像它的名字所暗示的那樣,將所需的標記轉換為畫布,然後我們可以簡單地將畫布元素下載為圖片。
示例
這樣做的程式碼如下 −
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <style> #capture{ height: 300px; width: 300px; display: flex; flex-direction: column; background-color: rgb(43, 216, 216); } span{ flex: 1; width: 100%; display: flex; text-align: center; justify-content: center; align-items: center; color: #ffffff; font-size: 20px; } #first{ background-color: rgb(15, 168, 15); } #second{ background-color: rgb(43, 93, 228); } #third{ background-color: rgb(194, 55, 13); } </style> <body> <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script> <script> const download = () => { html2canvas(document.querySelector('#capture')).then(canvas => { document.body.appendChild(canvas); }); } </script> <div id='capture'> <span id='first'>First Block</span> <span id='second'>Second Block</span> <span id='third'>Third Block</span> </div> <button onclick="download()"> Download </button> </body> </html>
輸出
下述程式碼的輸出如下 −
單擊下載按鈕後
請注意,第二個影像包含一個與“下載”按鈕相鄰的畫布,我們可以簡單地右鍵單擊它並將其儲存到我們的本地儲存。
廣告