我使用 javascript 创建了一个画布并将其附加到输出 div,我想获取该画布并将其作为 png 下载到客户端,但我找不到方法来做到这一点
我什至尝试了canva2image,但我无法让它工作 这是我的代码:
<!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="html2canvas.js"></script>
</head>
<body>
<div id="tabela"><p>this is a test</p></div>
<button onclick="takeshot()">Copy</button>
<div id="output"></div>
<script type="text/javascript">
// Define the function
// to screenshot the div
function takeshot() {
let div = document.getElementById('tabela');
html2canvas(div).then(
function(canvas) {
document
.getElementById('output')
.appendChild(canvas);
})
}
</script>
</body>
</html>
你可以使用这个js文件。
https://html2canvas.hertzen.com/dist/html2canvas.min.js
我在下面添加示例代码。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<style>
#myDiv {
background-color: lightgreen;
padding: 40px 20px;
color: blue;
}
</style>
<title>Download Div as PNG</title>
</head>
<body>
<div id="myDiv">
<h1>Hello, this is the content!</h1>
</div>
<button onclick="handleDownload()">Download as PNG</button>
<script>
function handleDownload() {
const divElement = document.getElementById("myDiv");
html2canvas(divElement).then((canvas) => {
const imgData = canvas.toDataURL("image/png");
const link = document.createElement("a");
link.href = imgData;
link.download = "div_image.png";
link.click();
});
}
</script>
</body>
</html>
你可以测试一下。
function handleDownload() {
const divElement = document.getElementById("myDiv");
html2canvas(divElement).then((canvas) => {
const imgData = canvas.toDataURL("image/png");
const link = document.createElement("a");
link.href = imgData;
link.download = "div_image.png";
link.click();
});
}
#myDiv {
background-color: lightgreen;
padding: 40px 20px;
color: blue;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<style>
</style>
<title>Download Div as PNG</title>
</head>
<body>
<div id="myDiv">
<h1>Hello, this is the content!</h1>
</div>
<button onclick="handleDownload()">Download as PNG</button>
</body>
</html>