使用 html2Canvas 创建下载 png 时出现以下错误
I am getting following error while creating download png using html2Canvas
我在创建网站时使用 html2canvas
将文本转换为图像。转换已成功完成,但在尝试点击按钮下载时,
我收到以下错误:
Error Screenshot
谁能帮我解决这个问题?
PS: 我是网页设计新手
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);
}
});
我在创建网站时使用 html2canvas
将文本转换为图像。转换已成功完成,但在尝试点击按钮下载时,
我收到以下错误:
Error Screenshot
谁能帮我解决这个问题?
PS: 我是网页设计新手
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);
}
});