我在使用html2Canvas创建下载png时遇到以下错误



在创建网站时,我使用了html2canvas,它将把文本转换为图像。转换已成功完成,但在尝试点击按钮下载时,我得到以下错误:错误屏幕截图

有人能帮我吗?

附言:我在网页设计方面完全是个新手

html2canvas(document.getElementById("myname"), {
onrendered: function (canvas) {
var screenshot = canvas.toDataURL("image/png");
document.getElementById("textScreenshot").setAttribute("src", screenshot);
},
});
btnDownload.addEventListener("click", function () {
if (window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(textScreenshot.msToBlob(), "sg.png");
} else {
const a = document.createElement("a");
document.body.appendChild(a);
a.href = screenshot.toDataURL();
a.download = "sg.png";
a.click();
document.body.removeChild(a);
}
});

错误:texttoimg.html:99未捕获引用错误:未定义屏幕截图在HTMLButtonElement上。

之所以会发生这种情况,是因为screenshot变量的本地作用域是onrendered函数。您需要将其取出并存储在全局变量中,以便能够在其他函数中访问它。

let screenshot; // making it global 
window.onload = function(){
html2canvas(document.getElementById("myname"), {
onrendered: function (canvas) {
screenshot = canvas.toDataURL("image/png");
document.getElementById("textScreenshot").setAttribute("src", screenshot);
},
});
}
btnDownload.addEventListener("click", function () {
if (window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(textScreenshot.msToBlob(), "sg.png");
} else {
const a = document.createElement("a");
document.body.appendChild(a);
a.href = screenshot; // remote toDataURL from here
a.download = "sg.png";
a.click();
document.body.removeChild(a);
}
});

最新更新