Search code examples
htmlcanvas

Unable to get canvas


I can't see why this code gives me an error line 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>

There is no CSS.


Solution

  • You're never actually trying to get it.

    In your code you've got this line. The first thing it does it check if canvas is not null, and if the function getContext is available. The following line sets canvas. It will always fail on that first check.

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

    Also noteworthy, in the HTML there's a missing quote causing your canvas' ID to be up for misinterpretation.

    <canvas id="canvas></canvas>
    

    Corrected code

    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>