<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Web页面转换为图片并下载</title>
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.0.0/html2canvas.min.js"></script> -->
<script async src="https://cdn.bootcdn.net/ajax/libs/html2canvas/1.4.1/html2canvas.js"></script>
</head>
<body>
<button onclick="downloadImage()">下载图片</button>
<canvas id="canvas"></canvas>
<script>
function downloadImage() {
// 获取要转换的Web页面
let html = document.documentElement;
// 使用html2canvas将Web页面转换为Canvas
html2canvas(html).then(function(canvas) {
// 将Canvas转换为DataURL
let dataURL = canvas.toDataURL('image/png');
console.log(dataURL)
// 创建新的Image对象并设置src
let img = new Image();
img.src = dataURL;
// 等待Image对象加载完成
img.onload = function() {
// 创建下载链接
let link = document.createElement('a');
link.href = dataURL;
link.download = 'webpage.png';
// 模拟单击下载链接
link.click();
};
});
}
</script>
</body>
</html>