如果想要製作將網頁其中一個區塊截圖並儲存圖片的功能,可以參考使用這兩個 plugin,都很簡單使用。
首先使用 html2canvas,這隻可以把你指定的區塊轉換為 canvas:
HTML 部分:
<div id="capture" style="padding: 10px; background: #f5da55">
<h4 style="color: #000; ">Hello world!</h4>
</div>
js 部分:
html2canvas(document.querySelector("#capture")).then(canvas => { document.body.appendChild(canvas) });
這樣就可以在指定的區域生成 canvas,之後再透過 canvas2imgae 轉換為圖片:
Canvas2Image.saveAsImage(canvasObj, width, height, type, fileName) Canvas2Image.saveAsPNG(canvasObj, width, height, fileName) Canvas2Image.saveAsJPEG(canvasObj, width, height, fileName) Canvas2Image.saveAsGIF(canvasObj, width, height, fileName) Canvas2Image.saveAsBMP(canvasObj, width, height, fileName) Canvas2Image.convertToImage(canvasObj, width, height, type) Canvas2Image.convertToPNG(canvasObj, width, height) Canvas2Image.convertToJPEG(canvasObj, width, height) Canvas2Image.convertToGIF(canvasObj, width, height) Canvas2Image.convertToBMP(canvasObj, width, height)
以上為支援的圖片格式,整合起來的 code 如下:
document.querySelector('button').addEventListener('click', function() { html2canvas(document.querySelector('.specific'), { onrendered: function(canvas) { // document.body.appendChild(canvas); return Canvas2Image.saveAsPNG(canvas); } }); });