画布 id 未在 javascript 中识别

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


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


索引.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>

客户端1.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 无法识别这一点。


慕虎7371278
浏览 124回答 2
2回答

眼眸繁星

快速修复:将document.writeclient1.js 中的调用替换为console.logdocument.addEventListener("DOMContentLoaded", function() {&nbsp; &nbsp;var mouse = {&nbsp; &nbsp; &nbsp; click: false,&nbsp; &nbsp; &nbsp; move: false,&nbsp; &nbsp; &nbsp; pos: {x:0, y:0},&nbsp; &nbsp; &nbsp; pos_prev: false&nbsp; &nbsp;};&nbsp; &nbsp;// get canvas element and create context&nbsp; &nbsp;var mouse = {&nbsp; &nbsp; &nbsp; click: false,&nbsp; &nbsp; &nbsp; move: false,&nbsp; &nbsp; &nbsp; pos: {x:0, y:0},&nbsp; &nbsp; &nbsp; pos_prev: false&nbsp; &nbsp;};&nbsp; &nbsp;// get canvas element and create context&nbsp; &nbsp;console.log("Hetoo&nbsp; &nbsp;");&nbsp; &nbsp;var canvas&nbsp; = document.getElementById("canvas");&nbsp; &nbsp;if(canvas)&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp;console.log("got her.");&nbsp; &nbsp;}&nbsp; &nbsp;else&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp;console.log(canvas);&nbsp; &nbsp;}&nbsp; &nbsp;console.log("&nbsp; Hepoo&nbsp; ");&nbsp; &nbsp;var context = canvas.getContext('2d');&nbsp; &nbsp;console.log("Heyoo&nbsp; ");})您还应该考虑将脚本标记移动到head元素中,并在必要时使用async或defer属性来控制它们的加载方式
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript