<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>html2canvas 长截图示例</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<style>
body {
font-family: Arial, sans-serif;
}
#capture {
width: 100%;
height: 1500px; /* 模拟长页面 */
background: linear-gradient(to bottom, #ff9a9e, #fad0c4);
padding: 20px;
text-align: center;
}
button {
margin: 20px;
padding: 10px 20px;
font-size: 16px;
}
</style>
</head>
<body>
<button onclick="captureScreen()">截取长截图</button>
<div id="capture">
<h1>html2canvas 长截图测试</h1>
<p>此页面高度较大,可用于测试滚动截图</p>
<div
style="
margin-bottom: 0;
width: 100%;
height: 1000px;
display: flex;
flex-direction: column-reverse;
"
>
底部
</div>
</div>
<script>
function captureScreen() {
const element = document.getElementById("capture");
html2canvas(element, {
useCORS: true, // 处理跨域问题
scrollX: 0,
scrollY: 0,
windowWidth: document.documentElement.scrollWidth, // 获取整个页面宽度
windowHeight: document.documentElement.scrollHeight, // 获取整个页面高度
}).then((canvas) => {
// 转换为图片
let image = canvas.toDataURL("image/png");
// 创建下载链接
let link = document.createElement("a");
link.href = image;
link.download = "screenshot.png";
link.click();
});
}
</script>
</body>
</html>
使用html2Canvas截取页面长图
最新推荐文章于 2025-04-23 17:03:07 发布