使用 html2canvas 动作只工作一次,我需要代码多次工作
Using html2canvas action is working just once and i need the code works multiple times
我正在使用一些 html2canvas 创建一个网络应用程序,想法是:用户上传照片,然后从库中选择一个 png 图像放置在图像上,用户可以下载贴有贴纸的图像。第一次一切正常,但是当我第二次尝试使用下载按钮时,什么也没有发生。控制台显示以下错误:
未捕获类型错误:无法在 HTMLButtonElement.capture (index.html:82)
处设置 属性 'id' of null
第82行是:body.id = 'CapturaPantalla';
我怎样才能每次都重置代码以便用户可以多次下载图像?
这是代码:
<script>
const capture = () => {
const body = document.querySelector('#ImagenLista');
body.id = 'CapturaPantalla';
html2canvas(document.querySelector("#CapturaPantalla")).then(canvas => {
document.body.appendChild(canvas);
}).then(() => {
var canvas = document.querySelector('canvas');
canvas.style.display = 'none';
var image = canvas.toDataURL("image/jpg").replace("image/jpg", "image/octet-stream");
var a = document.createElement("a");
a.setAttribute('download', 'YoSoyYVoyA.jpg');
a.setAttribute('href', image);
a.click();
});
};
const btn = document.getElementById('DescargaImagen');
function FuncionDescarga() {
btn.addEventListener('click', capture);
}
</script>
先谢谢大家了。
首先,您将获得一个元素:
const body = document.querySelector('#ImagenLista');
然后,您更改元素的 ID:
body.id = 'CapturaPantalla';
因此,当您再次转到 select 元素时,它具有不同的 ID,因此返回 null
。
解决方案应该是显而易见的,但如果由于某种原因你必须保留第 82 行,你可以这样做:
if (body) {
body.id = 'CapturaPantalla';
}
还有一个更压缩的版本:
body && (body.id = 'CapturaPantalla');
我正在使用一些 html2canvas 创建一个网络应用程序,想法是:用户上传照片,然后从库中选择一个 png 图像放置在图像上,用户可以下载贴有贴纸的图像。第一次一切正常,但是当我第二次尝试使用下载按钮时,什么也没有发生。控制台显示以下错误:
未捕获类型错误:无法在 HTMLButtonElement.capture (index.html:82)
处设置 属性 'id' of null第82行是:body.id = 'CapturaPantalla';
我怎样才能每次都重置代码以便用户可以多次下载图像?
这是代码:
<script>
const capture = () => {
const body = document.querySelector('#ImagenLista');
body.id = 'CapturaPantalla';
html2canvas(document.querySelector("#CapturaPantalla")).then(canvas => {
document.body.appendChild(canvas);
}).then(() => {
var canvas = document.querySelector('canvas');
canvas.style.display = 'none';
var image = canvas.toDataURL("image/jpg").replace("image/jpg", "image/octet-stream");
var a = document.createElement("a");
a.setAttribute('download', 'YoSoyYVoyA.jpg');
a.setAttribute('href', image);
a.click();
});
};
const btn = document.getElementById('DescargaImagen');
function FuncionDescarga() {
btn.addEventListener('click', capture);
}
</script>
先谢谢大家了。
首先,您将获得一个元素:
const body = document.querySelector('#ImagenLista');
然后,您更改元素的 ID:
body.id = 'CapturaPantalla';
因此,当您再次转到 select 元素时,它具有不同的 ID,因此返回 null
。
解决方案应该是显而易见的,但如果由于某种原因你必须保留第 82 行,你可以这样做:
if (body) {
body.id = 'CapturaPantalla';
}
还有一个更压缩的版本:
body && (body.id = 'CapturaPantalla');