试试这个:
在 HTML 中:
html2canvas.min.js
文件。在 JavaScript 中:
capture()
函数。capture()
函数绑定到您正在使用的任何事件 - 在本例中,它位于 btn click
事件上。HTML:
<h1 id="capture">Hellooooo</h1>
<button id="btn">Capture</button>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
Javascript:
function capture() {
const captureElement = document.querySelector('#capture') // Select the element you want to capture. Select the <body> element to capture full page.
html2canvas(captureElement)
.then(canvas => {
canvas.style.display = 'none'
document.body.appendChild(canvas)
return canvas
})
.then(canvas => {
const image = canvas.toDataURL('image/png')
const a = document.createElement('a')
a.setAttribute('download', 'my-image.png')
a.setAttribute('href', image)
a.click()
canvas.remove()
})
}
const btn = document.querySelector('#btn')
btn.addEventListener('click', capture)
💡快速提示:如果您想捕获整个文档/网页,只需将“捕获”ID 添加到
<body>
标签即可。
如果图像有黑色背景,您的图表必须在屏幕上可见。因为html2canvas就像截图一样。如果你想转换数据 到画布上,您必须确保数据出现在屏幕中。
如果有人使用 React,您可以复制以下代码:
async function download() {
const canvas = await html2canvas(document.querySelector("#screenshot"));
canvas.style.display = "none";
document.body.appendChild(canvas);
const image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
const a = document.createElement("a");
a.setAttribute("download", `info.png`);
a.setAttribute("href", image);
a.click();
}
<a href="#" onClick={() => download()}>Download</a>
这对我有用:
HTML
<div id="canvasDiv">
<canvas id="canvas" height="100" width="100">
Your browser does not support the HTML canvas tag.
</canvas>
</div>
<button onclick="screenShot()" type="button">Take a screenshot</button>
Javascript
function screenShot(){
html2canvas(document.querySelector("#canvasDiv")).then(canvas => {
var dataURL = canvas.toDataURL( "image/png" );
var data = atob( dataURL.substring( "data:image/png;base64,".length ) ),
asArray = new Uint8Array(data.length);
for( var i = 0, len = data.length; i < len; ++i ) {
asArray[i] = data.charCodeAt(i);
}
var blob = new Blob( [ asArray.buffer ], {type: "image/png"} );
saveAs(blob, "photo.png");
});
}
我刚刚使用了html2canvas网站中提供的代码,然后我使用此代码下载了屏幕截图。