[英]I am getting following error while creating download png using html2Canvas
While creating a website I was using html2canvas
which is going to convert text to an image.在创建网站时,我使用的是html2canvas
,它将文本转换为图像。 Conversion is done successfully but while trying to download on button click, I got the following error: Error Screenshot转换已成功完成,但在尝试单击按钮下载时,出现以下错误:错误屏幕截图
Can anyone help me out with this please?任何人都可以帮我解决这个问题吗?
PS: I am completely new in web designing PS:我在 web 设计方面是全新的
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);
}
});
Error:texttoimg.html:99 Uncaught ReferenceError: screenshot is not defined at HTMLButtonElement.错误:texttoimg.html:99 Uncaught ReferenceError:屏幕截图未在 HTMLButtonElement 中定义。
This is happening because your screenshot
variable is locally scoped to your onrendered
function.发生这种情况是因为您的screenshot
变量在本地范围内是您的onrendered
function。 You need to take it out and store in a global variable to be able to access it in the other function.您需要将其取出并存储在一个全局变量中,以便能够在另一个 function 中访问它。
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);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.