前言
前端实现页面截图通常有两种方式,分别为:
- canvas
- puppeteer
canvas实现
cdn方式引入
<script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
npm下载
npm install html2canvas
实现流程
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
</head><body><div id="screenshot-target" style="background: #f5f5f5;"><h1>要截图的内容</h1><p>这是一个示例内容</p></div><div>不在截图中的内容</div><button id="screenshot-btn">截图并下载</button><script>function takeScreenshot() {const targetElement = document.getElementById('screenshot-target'); // 要截图的元素IDhtml2canvas(targetElement).then((canvas) => {const imgData = canvas.toDataURL('image/png'); // 将canvas转换为图片// 下载const link = document.createElement('a');link.href = imgData;link.download = 'screenshot.png';link.click();});}document.getElementById('screenshot-btn').addEventListener('click', takeScreenshot);</script>
</body></html>