Cannot read property 'getContext' of null
Solution 1
Firstly, you should check for null:
var c = document.getElementById("canvas1");
if (c != null) {
// proceed
} else {
// a problem: what can you do about it?
}
Secondly, make sure you have an element canvas1
- if it exists then c
should not be null
; if it doesn't exist then there's a discrepancy between the code and content, and you need to decide what should happen in circumstances when this occurs, if it should never occur then it's exceptional and maybe you want the error the be raised, or a message of your own specified, or something.
Solution 2
I was using var ctx= c.getContext('2D');
with the capital 'D' in 2D and that is not correct. It should be a lowercase 'd' in 2d. I realize this is a very simple error, but it brought me here. Hopefully I no one else starts to pull out hair on something so simple.
Solution 3
Check the position of your script. I have included it in the <head>
section so obviously, it tried to find canvas
element even before letting it appended to the DOM. Thus giving undefined
or null
error.
Aditya.M
Updated on January 26, 2021Comments
-
Aditya.M over 3 years
I have a button which on click executes this function.This code is to draw a line on canvas element on which PDF file gets rendered on a webpage by using PDF.JS. But i get an error "Uncaught TypeError: Cannot read property 'getContext' of null". What should i do.
function abc() { alert("msg"); var c=document.getElementById("canvas1"); alert(c); var ctx= c.getContext('2d'); alert(ctx); ctx.beginPath(); ctx.moveTo(0,0); ctx.lineTo(300,150); ctx.stroke(); }
-
Aditya.M about 10 yearsIm using pdf.js to render a pdf file on my website. I am not able to access the canvas on which the pdf file gets rendered on. this code is a part of the program. I have tried your solution and apparently 'c' is null. please help me if you know about pdf.js. Appreciate your help.
-
markE about 10 yearsNothing wrong...I suspect OP has issue somewhere else in his code. +1 to reverse someone else's minuses.
-
Dissident Rage about 10 yearsIf
c
isnull
then you don't have a canvas withid="canvas1"
. Change it to the ID of your canvas. -
Slayer Of Whales almost 3 yearsThis answer has just saved my life. I was so confused, for such a simple error it is disappointing that there is no real way to detect it.