Anish Sana Anish Sana - 1 month ago 11
CSS Question

Canvas - Uncaught TypeError: Cannot read property 'getContext' of null

I'm new to Canvas and was trying it out on Codepen. I keep getting the error -

Uncaught TypeError: Cannot read property 'getContext' of null


I've read a lot of similar questions about the same error on StackOverflow and tried some of the solutions provided but none of them seem to work.

Is this because the HTML is being loaded before JavaScript as some of the answers seem to suggest? Unfortunately, I don't think I can make that change on Codepen.

I've also tried wrapping it in
$( document ).ready(function() {});
using jQuery but that didn't work either.

Basically, I have this
<canvas>
element -
<canvas id="mycanvas" class="orangeback"></canvas>

where I'm trying to create a rectangle and some text using the JavaScript below -

function doRed() {
var id1 = document.getElementById("mycanvas");
id1.style.backgroundColor = "red";
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.fillStyle = "purple";
context.fillRect(10,10,60,60);

context.fillStyle = "black";
context.font = "30px Arial";
context.text = "Hello";
}


Here's the link to my full code on JSFiddle

It would be helpful if someone can point to me what's going wrong. Thanks!

Answer

Your script had a typo error myCanvas should be instead mycanvas. You also query for canvas few times, you can minimize dom query using the result of document.getElementById() in a variable.

Example below:

// cache result
var canvas = document.getElementById("mycanvas"),
context = canvas.getContext("2d");

function doRed() {
  context.clearRect(0, 0, canvas.width, canvas.height);
  canvas.style.backgroundColor = "red";    
  context.fillStyle = "purple";
  context.fillRect(10,10,60,60);    
  context.fillStyle = "black";
  context.font = "30px Arial";
  context.fillText= "Hello";
}

function doBlue() {
  context.clearRect(0, 0, canvas.width, canvas.height);
  canvas.style.backgroundColor = "blue";
}
h1 {
  color: red;
}

div {
  background-color: yellow;
}

#div1 {
  font-family: helvetica;
}

#div2 {
  font-size: 36px;
}

.orangeback {
  background-color: orange;
}

.yellowback {
  background-color: yellow;
}

.blueback {
  background-color: blue;
}

.pinkback {
  background-color: pink;
}

canvas {
  width: 200px;
  height: 100px;
}
<h1>Main Header</h1>
<canvas id="mycanvas" class="orangeback">
</canvas>
<input type="button" value="red" id="button2" onclick="doRed()">
<input type="button" value="blue" id="button3" onclick="doBlue()">