Skip to content

Instantly share code, notes, and snippets.

@qichunren
Created October 28, 2024 03:55
Show Gist options
  • Save qichunren/7f5896d83f1ed12fb04e10054c96f92c to your computer and use it in GitHub Desktop.
Save qichunren/7f5896d83f1ed12fb04e10054c96f92c to your computer and use it in GitHub Desktop.
html page to image
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>页面转图片</title>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
#content {
border: 1px solid #ddd;
padding: 20px;
margin-bottom: 20px;
background-color: aquamarine;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
#output {
margin-top: 20px;
}
#output img {
max-width: 100%;
height: auto;
border: 1px solid #ddd;
}
</style>
</head>
<body>
<div id="content">
<!-- 这里是要转换成图片的内容 -->
<h1>Hello, World!</h1>
<p>这是一个示例页面。</p>
</div>
<button onclick="convertToImage()">转换为图片</button>
<div id="output"></div>
<script>
function convertToImage() {
html2canvas(document.querySelector("#content")).then(canvas => {
try {
// 设置最大宽度和高度
const maxWidth = 800;
const maxHeight = 600;
// 计算缩放比例
const scale = Math.min(maxWidth / canvas.width, maxHeight / canvas.height);
// 创建一个新的canvas,保持原始比例
const newCanvas = document.createElement('canvas');
newCanvas.width = canvas.width * scale;
newCanvas.height = canvas.height * scale;
// 将原始canvas内容绘制到新canvas上
const ctx = newCanvas.getContext('2d');
ctx.scale(scale, scale);
ctx.drawImage(canvas, 0, 0);
// 转换为图片并显示在页面上
const image = newCanvas.toDataURL("image/png");
const img = document.createElement('img');
img.src = image;
document.getElementById('output').innerHTML = '';
document.getElementById('output').appendChild(img);
} catch (error) {
console.error("Error generating image:", error);
alert("生成图片时出错,请查看控制台以获取详细信息。");
}
}).catch(error => {
console.error("Error with html2canvas:", error);
alert("html2canvas 出错,请查看控制台以获取详细信息。");
});
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment