Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用html2canvas操作只工作一次,我需要代码工作多次_Javascript_Html2canvas - Fatal编程技术网

Javascript 使用html2canvas操作只工作一次,我需要代码工作多次

Javascript 使用html2canvas操作只工作一次,我需要代码工作多次,javascript,html2canvas,Javascript,Html2canvas,我正在使用一些html2canvas创建一个web应用程序,其想法是:用户上传一张照片,然后从库中选择一个png图像放置在图像上,用户可以下载粘贴了标签的图像。第一次一切正常,但当我第二次尝试使用下载按钮时,什么也没发生。控制台显示以下错误: 未捕获的TypeError:无法在HtmlButtoneElement.capture(index.html:82)处将属性“id”设置为null 行号82是:body.id='CapturaPantalla' 我如何每次重置代码,以便用户可以多次下载图像

我正在使用一些html2canvas创建一个web应用程序,其想法是:用户上传一张照片,然后从库中选择一个png图像放置在图像上,用户可以下载粘贴了标签的图像。第一次一切正常,但当我第二次尝试使用下载按钮时,什么也没发生。控制台显示以下错误:

未捕获的TypeError:无法在HtmlButtoneElement.capture(index.html:82)处将属性“id”设置为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”);
body.id='CapturaPantalla';
html2canvas(document.querySelector(#CapturaPantalla”)。然后(canvas=>{
document.body.appendChild(画布);
}).然后(()=>{
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',图像);
a、 单击();
});
};
const btn=document.getElementById('DescargaImagen');
函数functiondescarga(){
btn.addEventListener(“点击”,捕获);
}

提前感谢大家。

首先,您将获得一个元素:

const body=document.querySelector(“#ImagenLista”);
然后,更改元素的ID:

body.id='CapturaPantalla';
因此,当您再次选择元素时,它具有不同的ID,因此返回
null

解决方案应该是显而易见的,但如果出于某种原因您必须保留第82行,您可以这样做:

if(主体){
body.id='CapturaPantalla';
}
以及更为压缩的版本:

body&(body.id='CapturaPantalla');