【问题标题】:canvas id not being recongized in javascriptjavascript中无法识别画布ID
【发布时间】:2019-06-09 18:11:26
【问题描述】:

我试图找出为什么我的 html canvas 元素在 javascript 中无法被识别。

我不确定为什么我的画布元素为空。我在 html 中定义了它,并且只有在触发 DOMContentLoaded 事件后才运行 javascript。

index.html:

<!DOCTYPE html>
<html>
   <head>
      <title>Whiteboard</title>
      <meta charset="utf-8">
      <link rel="stylesheet" href="style.css" />
   </head>
   <body>
      <canvas id="canvas">Your browser doesn't support "canvas".</canvas>
      <!--<script src="/node_modules/socket.io/socket.io.js"></script>-->
      <script type="text/javascript" src="client1.js"></script>
   </body>
</html>

client1.js:

 document.addEventListener("DOMContentLoaded", function() {
       var mouse = { 
          click: false,
          move: false,
          pos: {x:0, y:0},
          pos_prev: false
       };
       // get canvas element and create context
       document.write("Hetoo   ");
       var canvas  = document.getElementById("canvas");
       if(canvas)
       {
           document.write("got her.");
       }
       else
       {
           document.write(canvas);
       }
       document.write("  Hepoo  ");
       var context = canvas.getContext('2d');
       document.write("Heyoo  ");
 }

网页输出:

Hetoo null Hepoo

我希望画布不为空,但由于某种原因 javascript 无法识别。

【问题讨论】:

标签: javascript


【解决方案1】:

有关为什么会发生这种情况的解释,请参阅:JavaScript Document.Write Replaces All Body Content

快速修复:将 client1.js 中的 document.write 调用替换为 console.log

document.addEventListener("DOMContentLoaded", function() {
   var mouse = {
      click: false,
      move: false,
      pos: {x:0, y:0},
      pos_prev: false
   };
   // get canvas element and create context
   var mouse = {
      click: false,
      move: false,
      pos: {x:0, y:0},
      pos_prev: false
   };
   // get canvas element and create context
   console.log("Hetoo   ");
   var canvas  = document.getElementById("canvas");
   if(canvas)
   {
       console.log("got her.");
   }
   else
   {
       console.log(canvas);
   }
   console.log("  Hepoo  ");
   var context = canvas.getContext('2d');
   console.log("Heyoo  ");
})

您还应该考虑将您的脚本标签移动到head 元素中,并在必要时使用asyncdefer 属性来控制它们的加载方式

【讨论】:

    【解决方案2】:

    我正在获取上下文对象尝试下面的代码并告诉我

    var canvas = document.getElementById("canvas");
            console.dir(canvas.getContext('2d'));
    &lt;canvas id="canvas"&gt;Your browser doesn't support "canvas".&lt;/canvas&gt;

    【讨论】:

      【解决方案3】:

      如果您删除 DOMContentLoaded 侦听器,它应该可以工作,请参阅此答案:

      Code inside DOMContentLoaded event not working

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-27
        • 2011-11-02
        • 2014-02-20
        • 1970-01-01
        • 1970-01-01
        • 2012-08-21
        • 1970-01-01
        • 2014-01-18
        相关资源
        最近更新 更多