【问题标题】:Unable to get canvas无法获取画布
【发布时间】:2022-08-24 03:44:14
【问题描述】:

我不明白为什么这段代码给了我第 11 行错误

 if (canvas.getContext) {...

<!DOCTYPE html>
<html lang=\"en-US\">
  <head>
    <meta charset=\"UTF-8\"/>
    <title>Peripheral vision checker</title>

  <script type=\"application/javascript\">

    function draw() { if (canvas.getContext) {
      const canvas = document.getElementById(\'canvas\');
      if (canvas.getContext) {
        const ctx = canvas.getContext(\'2d\');

        function getRandomInt(max) {
        return Math.floor(Math.random() * max);
        }
        var x = 1000;//will be equal to window height
        var y = 100;//will be equal to window width
        ctx.arc(getRandomInt(x), getRandomInt(y), 10, 0, 2 * Math.PI);

        console.log(getRandomInt(x) + \" \" + getRandomInt(y));//just temporary to see they work

        ctx.fill();
    }

  }

  </script>
 </head>
 <h1>Peripheral vision checker</h1>
 <body onload=\"draw();\">
   <canvas id=\"canvas></canvas>
 </body>
</html>

没有CSS。

    标签: html canvas


    【解决方案1】:

    你从来没有真正试图得到它。

    在您的代码中,您有这一行。它首先检查canvas 是否不为空,以及函数getContext 是否可用。以下行 设置canvas。第一次检查总是会失败。

    function draw() { if (canvas.getContext) {
    

    同样值得注意的是,在 HTML 中缺少引号会导致您的画布 ID 被误解。

    <canvas id="canvas></canvas>
    

    更正的代码

    function draw() {
      const canvas = document.getElementById('canvas');
      const ctx = canvas.getContext('2d');
    
      if (ctx) {
        function getRandomInt(max) {
          return Math.floor(Math.random() * max);
        }
        var x = 100; //will be equal to window height
        var y = 100; //will be equal to window width
        ctx.arc(getRandomInt(x), getRandomInt(y), 10, 0, 2 * Math.PI, 0);
    
        console.log(getRandomInt(x) + " " + getRandomInt(y)); //just temporary to see they work
        ctx.fillColor = "black";
    
    
        ctx.fill();
      }
    }
    <body onload="draw();">
      <canvas id="canvas"></canvas>
    </body>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-12
      • 2014-11-06
      • 1970-01-01
      • 1970-01-01
      • 2016-06-11
      • 2021-07-03
      • 2022-01-10
      相关资源
      最近更新 更多