1. 簡介
html2canvas
是一個用于將 HTML 頁面或特定 DOM 元素轉換為 Canvas 畫布的 JavaScript 庫。它通過解析 HTML 和 CSS,生成等效的 Canvas 圖像,從而實現網頁截圖功能。
2. 安裝
可以使用 npm 或 yarn 安裝 html2canvas
,也可以通過 CDN 引入:
使用 npm 安裝
npm install html2canvas --save
使用 yarn 安裝
yarn add html2canvas
通過 CDN 引入
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
3. 基本使用方法(TypeScript)
import html2canvas from "html2canvas";document.getElementById("capture-btn")?.addEventListener("click", () => {const element = document.getElementById("capture-area");if (element) {html2canvas(element).then((canvas: HTMLCanvasElement) => {document.body.appendChild(canvas); // 將截圖添加到頁面});}
});
在 HTML 代碼中:
<div id="capture-area"><h1>要截圖的區域</h1>
</div>
<button id="capture-btn">截圖</button>
4. 配置選項
html2canvas
提供了一些可選的配置參數,可以優化截圖效果。
html2canvas(element as HTMLElement, {scale: 2, // 提高分辨率useCORS: true, // 允許跨域資源backgroundColor: "#ffffff", // 設置背景顏色,避免透明背景logging: false // 禁用日志輸出
}).then((canvas: HTMLCanvasElement) => {document.body.appendChild(canvas);
});
常見配置參數:
參數 | 說明 | 默認值 |
---|---|---|
scale | 生成的 Canvas 分辨率倍數 | window.devicePixelRatio |
useCORS | 允許加載跨域圖片 | false |
backgroundColor | 畫布背景顏色 | null (透明) |
logging | 是否在控制臺輸出日志 | true |
5. 下載截圖
如果想將生成的截圖下載為圖片,可以使用 toDataURL
方法:
html2canvas(document.getElementById("capture-area") as HTMLElement).then((canvas: HTMLCanvasElement) => {const link = document.createElement("a");link.href = canvas.toDataURL("image/png");link.download = "screenshot.png";link.click();
});
6. 解決常見問題
1. 跨域圖片無法截圖
由于安全限制,html2canvas
默認不支持跨域圖片。可以使用 useCORS: true
并確保圖片服務器支持 Access-Control-Allow-Origin
頭。
2. 某些 CSS 樣式未生效
html2canvas
并不能完美解析所有 CSS 樣式,特別是 position: fixed
、box-shadow
等。可以嘗試使用 foreignObjectRendering: true
。
html2canvas(element as HTMLElement, {foreignObjectRendering: true
}).then((canvas: HTMLCanvasElement) => {document.body.appendChild(canvas);
});
3. 文字模糊或圖片失真
可以設置 scale: window.devicePixelRatio * 2
來提高清晰度。
html2canvas(element as HTMLElement, { scale: 2 }).then((canvas: HTMLCanvasElement) => {document.body.appendChild(canvas);
});
7. 結論
html2canvas
是一個強大的網頁截圖工具,適用于生成網頁預覽圖、導出為圖片等場景。通過合理的配置和優化,可以提高截圖的質量和兼容性。如果需要更強大的功能,如完整網頁截圖,建議結合 puppeteer
等其他工具使用。