一、完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>HTML to Canvas Image</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.5.0-beta4/html2canvas.min.js"></script>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
display: flex;
justify-content: center;
align-items: center;
width: 400px;
height: 200px;
background-color: lightblue;
display: flex;
justify-content: center;
align-items: center;
border-radius: 20px;
position: relative;
overflow: hidden;
}
.img {
width: 100%;
position: absolute;
object-fit: cover;
z-index: 10;
}
.title {
position: absolute;
z-index: 11;
}
#generateButton {
margin-left: 5%;
}
</style>
</head>
<body>
<div class="container" id="container">
<h1 class="title">Sample Content</h1>
<img class="img" src="./img/1.jpg" alt="" />
</div>
<button id="generateButton">Generate and Download Image</button>
<script>
const container = document.getElementById("container");
const generateButton = document.getElementById("generateButton");
generateButton.addEventListener("click", () => {
html2canvas(container).then((canvas) => {
const image = canvas.toDataURL("image/png");
// 创建一个下载链接并触发下载
const a = document.createElement("a");
a.href = image;
a.download = "generated_image.png";
a.click();
});
});
</script>
</body>
</html>