html2canvas 是純 JS 實現的客戶端截圖庫,遍歷 DOM 計算樣式,在 `
<!-- HTML 引入 -->
<script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
<!-- 或 npm -->
npm install html2canvas
<div id="capture-area">
<h1>這是要截圖的區域</h1>
<p>包含文字、圖片、CSS 樣式...</p>
<img src="logo.png" alt="Logo">
</div>
<button id="btn-save">保存為圖片</button>
document.getElementById('btn-save').addEventListener('click', async () => {
const element = document.getElementById('capture-area');
const btn = document.getElementById('btn-save');
btn.disabled = true;
btn.textContent = '生成中...';
try {
// 核心 API
const canvas = await html2canvas(element, {
useCORS: true, // 支援跨域圖片(需圖片伺服器配置 Access-Control-Allow-Origin)
scale: 2, // 2倍縮放,提高清晰度
logging: false,
backgroundColor: '#fff' // 背景色,預設透明
});
// 轉為圖片下載
const dataUrl = canvas.toDataURL('image/png', 1.0);
const link = document.createElement('a');
link.href = dataUrl;
link.download = `webpage_${Date.now()}.png`;
link.click();
} catch (err) {
console.error('截圖失敗', err);
alert('截圖失敗,請查看控制台');
} finally {
btn.disabled = false;
btn.textContent = '保存為圖片';
}
});
| 選項 | 用途 | 建議值 |
|---|---|---|
scale | 縮放倍數,解決高 DPI 模糊 | window.devicePixelRatio 或 2 |
useCORS | 嘗試跨域載入圖片 | true(需圖片端支援 CORS) |
backgroundColor | Canvas 背景色 | '#ffffff' 或 null(透明) |
ignoreElements | 過濾不需截圖的元素 | (el) => el.id === 'btn-save' |
onclone | 克隆文檔後回調,可修改樣式 | 隱藏滾動條、修正 fixed 定位 |
<!-- Vue 3 組件範例 -->
<script setup>
import html2canvas from 'html2canvas';
const targetRef = ref(null);
const capture = async () => {
const canvas = await html2canvas(targetRef.value, { scale: 2 });
// 下載邏輯...
};
</script>
<template>
<div ref="targetRef">...內容...</div>
<button @click="capture">截圖</button>
</template>
html2canvas 適合「用戶主動觸發、當前可視區域、結構相對固定」的輕量截圖需求。複雜報表、PDF 導出、後端定時生成請轉向 Puppeteer/Playwright 等無頭瀏覽器方案。