Cannot read property 'getContext' of null

29,837

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.

Share:
29,837
Aditya.M
Author by

Aditya.M

Updated on January 26, 2021

Comments

  • Aditya.M
    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
    Aditya.M about 10 years
    Im 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
    markE about 10 years
    Nothing wrong...I suspect OP has issue somewhere else in his code. +1 to reverse someone else's minuses.
  • Dissident Rage
    Dissident Rage about 10 years
    If c is null then you don't have a canvas with id="canvas1". Change it to the ID of your canvas.
  • Slayer Of Whales
    Slayer Of Whales almost 3 years
    This 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.