DIV CSS 佈局教程網

借助 html2canvas 將網頁保存為圖片的實作
編輯:關於JavaScript     

將網頁內容保存為圖片是一個實用的功能,可應用於分享、存檔、截圖等場景。整個流程可分為兩個步驟。

第一步:把網頁保存為 Canvas 畫布

借助 html2canvas 庫(官網:https://html2canvas.hertzen.com/)可以輕鬆完成:

 html2canvas(document.getElementById("id1"), { onrendered: function(canvas) { document.getElementById("id2").appendChild(canvas);//生成畫布後如何處理 }, canvas_id: 'canvas' });

其中第一個參數為要生成 canvas 的區域,若要整個網頁生成則傳入 document.body;第二個參數用於設定 canvas 的各種屬性。

第二步:把生成的 canvas 保存成圖片

 var canvas = document.getElementById("canvas"), url = canvas.toDataURL(); var triggerDownload = $("<a>").attr("href", url).attr("download", "img.png").appendTo("body"); triggerDownload[0].click(); triggerDownload.remove();

這裡的關鍵是 toDataURL() 方法,它能將 canvas 轉換為 data 形式的圖片網址,把這個網址賦給 img 標籤即可顯示圖片,其餘程式碼則負責觸發下載功能。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved