简体   繁体   English

未捕获的类型错误:尝试下载图像 javascript 时无法读取 null 的属性(读取“src”)

[英]Uncaught TypeError: Cannot read properties of null (reading 'src') while trying to download image javascript

Hello i am creating an Qrcode generator, that after getting generated, i want to download it.您好,我正在创建一个 Qrcode 生成器,生成后,我想下载它。 i was able to use this code, and it worked at first, however i added a lot more code in my project, and it stopped working, with me getting this error我能够使用这段代码,一开始它可以工作,但是我在我的项目中添加了更多代码,它停止工作,我得到了这个错误

(index):337 Uncaught TypeError: Cannot read properties of null (reading 'src')
    at downloadcode ((index):337:51)
    at HTMLButtonElement.onclick ((index):74:91)

This is the html where my qrcode is generated, and the button where my click function is这是我的二维码生成的html,我点击function的按钮是

 <!-- Div criada para criar o qrcode 1000x1000 que será utilizado no download, não sendo visivel
      na pagina-->
      <div id="download" style="display: none;"></div>


      <button disabled id="download_button" class="formbold-btn" onclick="downloadcode()">
        Descarregar QR code
      </button>

This is my downloadcode method这是我的下载代码方法

  // Função que faz o download do qrcode em jpg
    function downloadcode() {

      var link = document.createElement("a");
      link.download = "qrcode.jpg";



      var teste = document.getElementById("download");


      link.href = teste.querySelector('img').src;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);


    }

This is how i make my QrCode (using easyqrcode.js) i don't think this is the matter, because i tried generate, like i was when it worked, but unfortunately this time hasn't worked, but i put it here anyway这就是我制作 QrCode 的方式(使用 easyqrcode.js) 我不认为这是问题,因为我尝试生成,就像我在它工作时一样,但不幸的是这次没有工作,但我还是把它放在这里

var options_download = {
        text: texto,
        width: 1000,
        height: 1000,
        colorDark: $('input[name="favcolor"]').val(),
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H,

        logoWidth: 475, // fixed logo width. default is `width/3.5`
        logoHeight: 475, // fixed logo height. default is `heigth/3.5`
        logo: imagem, // Relative address, relative to `easy.qrcode.min.js`
        logoBackgroundColor: '#fffff', // Logo backgroud color, Invalid when `logBgTransparent` is true; default is '#ffffff'
        logoBackgroundTransparent: false, // Whether use transparent image, default is false

      }

      new QRCode(document.getElementById("download"),options_download);

I understand that the error is saying that teste.querySelector('img').src is null, but i can't understand why, since it worked before (with the same code for the download function and the htlm)我知道错误是说 teste.querySelector('img').src 是 null,但我不明白为什么,因为它以前工作过(下载 function 和 html 的代码相同)

Thank you in advance先感谢您

Edit: to explain more what i am trying to do.编辑:更多地解释我想做什么。 I generate a QRcode, that appears on my Div with the ID = download, and then by clicking in the download button, i want to download it.我生成了一个二维码,它出现在我的 Div 上,ID = 下载,然后单击下载按钮,我想下载它。 Even without using img tags, it was working i added my complete html即使不使用 img 标签,它也能正常工作,我添加了完整的 html


      <div class="tab">
        <button class="tablinks" onclick="openForm(event, 'telephone')">Contacto</button>
        <button class="tablinks" onclick="openForm(event, 'email')">Email</button>
        <button class="tablinks" onclick="openForm(event, 'url')">Website</button>
        <button class="tablinks" onclick="openForm(event, 'maps')">Localização</button>
        <button class="tablinks" onclick="openForm(event, 'personal')">Personalizado</button>
      </div>

      <!--No input text, relativo ao código hexadecimal da cor, foi definido autocomplete="iasnsdijsdn" , visto
que autocomplete="off" é ignorado nos browsers mais recentes, quando se pretende desligar o autofill
(uma vez que quando se preenchia o formulario com os dados previamente guardados, a caixa relativa à
cor, era automaticamente preenchida com o email), e desta forma, faz com que essa caixa, não seja 
automaticamente preenchida-->
      <form id="form" autocomplete="off">
        <input type="text" id="name" name="name" placeholder="Inserir Nome" class="formbold-form-input" />
        <input type="tel" id="telephone" name="telephone" placeholder="Inserir Contacto Telefone"
          class="formbold-form-input" />
        <input type="email" id="email" name="email" placeholder="Inserir Email" class="formbold-form-input" />
        <input type="website" id="url" name="url" placeholder="Inserir Website" class="formbold-form-input" />
        <input type="website" id="maps" name="maps" placeholder="Inserir Ligação Google Maps"
          class="formbold-form-input" />
        <label id="labelcolor" for="favcolor">Definir cor: </label>
        <input type="color" onchange="changeCol()" id="favcolor" name="favcolor" value="#000000"
          class="formbold-form-input" />
        <input type="text" autocomplete="iasnsdijsdn" onchange="changeColBox()" id="colorcode" name="colorcode"
          value="#000000" class="formbold-form-input" />
        <label for="image" class="btn btn-primary btn-block btn-outlined">Upload Logo (opcional)</label>
        <input type="file" onchange="encodeImageFileAsURL(this)" style="display: none"
          accept="image/jpeg, image/png, image/jpg" id="image" name="image" class="formbold-form-input">
      </form>
      <button id="button" class="formbold-btn" onclick="generatecode(this.value)">
        Gerar QR code
      </button>

      <div id="qrcodes">
        <div id="qrcode_1" class="text-center"></div>
        <div id="qrcode_2" class="text-center"></div>
      </div>


  
      <div id="download" style="display: none;"></div>
      <!-- Div criada para criar o qrcode 1000x1000 que será utilizado no download, não sendo visivel
      na pagina-->
      


      <button disabled id="download_button" class="formbold-btn" onclick="downloadcode()">
        Descarregar QR code
      </button>

    </div>
  </div>

And this is my old Html这是我的旧电话 Html

 
      <input type="text" name="name" placeholder="Inserir Nome" class="formbold-form-input" />
      <input type="tel" name="telephone" placeholder="Inserir Contacto Telefone" class="formbold-form-input" />
      <input type="email" name="email" placeholder="Inserir Email" class="formbold-form-input" />
      <input type="website" name="url" placeholder="Inserir Website" class="formbold-form-input" />

      <button class="formbold-btn" onclick="generatecode()">
        Gerar QR code
      </button>


      <div id="qrcodes">
        <div id="qrcode_1" class="text-center"></div>
        <div id="qrcode_2" class="text-center"></div>
      </div>

      <!-- Div criada para criar o qrcode 1000x1000 que será realizado o download, não sendo visivel
      na pagina-->
      <div id="download" style="display: none;"></div>


      <button id="download_button" class="formbold-btn" onclick="downloadcode()">
        Descarregar QR code
      </button>

    </div>
  </div>

My old wait of generate the qrcode我的旧等待生成二维码

  new QRCode(document.getElementById("download"),


          {
            text: 'MECARD:' + 'N:' + name +
              ';TEL:' + $('input[name="telephone"]').val() +
              ';EMAIL:' + $('input[name="email"]').val() +
              ';URL:' + $('input[name="url"]').val() +
              ';;',
            width: 1000,
            height: 1000,
            colorDark: "#000000",
            colorLight: "#ffffff",
            correctLevel: QRCode.CorrectLevel.H

          });

And the download function和下载function

/ Função que faz o download do qrcode em jpg
    function downloadcode() {

      var link = document.createElement("a");
      link.download = "qrcode.jpg";



      var teste = document.getElementById("download");


      link.href = teste.querySelector('img').src;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

EDIT 2:编辑 2:

After trying several stuff, if i use在尝试了几种东西之后,如果我使用

<img src="data:image/gif;base64,R0lGODlhAQABAAAAACwAAAAAAQABAAA=" id="download" />

instead of代替

 <div id="download" class="text-center"></div>

the qrcode i try to generate the Qrcode to the img element, however my img continues blank. qrcode 我尝试生成 img 元素的 Qrcode,但是我的 img 继续空白。

However if i let my «download» stay only as a div, my Qrcore appear in it, as it should be.但是,如果我让我的“下载”仅作为一个 div,我的 Qrcore 就会出现在其中,因为它应该如此。 However after that happen, since it is not a img element, i am having problems in trying to get the URL (if i could get it, i think my problem would be solved)然而在那之后,因为它不是 img 元素,我在尝试获取 URL 时遇到了问题(如果我能得到它,我想我的问题就会解决)

Thank You again再次感谢你

Solved my problem!解决了我的问题! Was able to find this tutorial https://www.studentstutorial.com/javascript/convert-html-div-element using html2canvas, was able to turn my Div into a image, and then download it as normal能够使用 html2canvas 找到本教程https://www.studentstutorial.com/javascript/convert-html-div-element ,能够将我的 Div 转换为图像,然后正常下载

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 javascript Uncaught TypeError:无法读取null的属性(读取&#39;querySelector&#39;) - javascript Uncaught TypeError: Cannot read properties of null (reading 'querySelector') 未捕获的类型错误:无法读取 javaScript 中的 null 的属性(读取“addEventListener”) - Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') in javaScript 未捕获的类型错误:无法读取 null 的属性(读取“值”)javascript - Uncaught TypeError: Cannot read properties of null (reading 'value') javascript 未捕获的类型错误:无法读取 javaScript 中 null 的属性(读取“值”) - Uncaught TypeError: Cannot read properties of null (reading 'value') in javaScript Uncaught (in promise) TypeError: Cannot read properties of null (reading 'iso3166_1Alpha2') / 试图跳过 null 但不能 - Uncaught (in promise) TypeError: Cannot read properties of null (reading 'iso3166_1Alpha2') / Trying to skip null but cannot 未捕获的类型错误:无法读取 null 的属性(正在读取“切片”)------ 未捕获的类型错误:无法读取未定义的属性(正在读取“过滤器”) - Uncaught TypeError: Cannot read properties of null (reading 'slice') ------ Uncaught TypeError: Cannot read properties of undefined (reading 'filter') 未捕获的类型错误:无法读取 null 的属性(读取“uid”)。 试图获取 currentUser.uid - Uncaught TypeError: Cannot read properties of null (reading 'uid'). Trying to get the currentUser.uid Javascript 未捕获的 TypeError:无法读取 null 的属性“src” - Javascript uncaught TypeError: Cannot read property 'src' of null React, getting Uncaught TypeError: Cannot read properties of null (reading "useRef") while using React Router Dom - React, getting Uncaught TypeError: Cannot read properties of null (reading "useRef") while using React Router Dom 未捕获的类型错误:无法读取 null 的属性(读取“vlaue”) - Uncaught TypeError: Cannot read properties of null (reading 'vlaue')
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM