Papples
Papples

Reputation: 33

Javascript Cannot read property 'getContext' of Null, but <script> is after <canvas> and IDs match

I understand that this question is asked a lot, but the solution is usually that canvas is loaded after script, but I don't believe that's the case for me. Here's the HTML I'm sending to chrome:

<html>
<body>
<canvas id="myCanvas" width="578" height="200" style="border:1px solid #000000;">
</canvas>
<script>

main();

//
// start here
//
function main() {
  const canvas = document.querySelector("myCanvas");
  // Initialize the GL context
  const gl = canvas.getContext("webgl");

  // Only continue if WebGL is available and working
  if (!gl) {
    alert("Unable to initialize WebGL. Your browser or machine may not support 
    it.");
    return;
  }

  // Set clear color to black, fully opaque
  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  // Clear the color buffer with specified clear color
  gl.clear(gl.COLOR_BUFFER_BIT);
}
</script>
</body>
</html>

What is it that I'm doing wrong?

Upvotes: 1

Views: 6796

Answers (2)

kish
kish

Reputation: 161

try with :

const canvas = document.getElementById("myCanvas"); 

Upvotes: 0

Shubham Khatri
Shubham Khatri

Reputation: 281696

You need to specify a valid query to querySelector like

const canvas = document.querySelector("#myCanvas");

or use

const canvas = document.getElementById("myCanvas");

Upvotes: 2

Related Questions