javascript - 使用 html2Canvas 创建下载 png 时出现以下错误
问题描述
在创建一个网站时,我正在使用html2canvas
它将文本转换为图像。转换已成功完成,但在尝试单击按钮下载时,出现以下错误:
错误屏幕截图
任何人都可以帮我解决这个问题吗?
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 未捕获的 ReferenceError:屏幕截图未在 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);
}
});
推荐阅读
- c++ - C++ 模板类头文件/实现 - 涉及模板类的函数
- sql - 使用 join 时出错,join 会产生错误
- java - 为什么我会收到 NoSuchElementException?
- ios - 异步任务后在 SwiftUI 中的正确导航方式
- file - 重新编辑现有游戏
- javascript - 获取负数组索引
- mysql - 选择具有关系的多对多数据并在结果中添加新列
- android - 应用程序:compileDebugJavaWithJavac'。> 找不到 tools.jar 无法启动模拟器。原因:没有找到模拟器作为 `emulator -list-avds` 的输出
- html - 将图片链接作为道具传递
- laravel - Laravel 8 向 CopyAndPay Api 发出 POST 请求并呈现表单