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();
}
Assuming your alerts report that you have valid references to your canvas and context:
Alert#1:
HTMLCanvasElement
andAlert#2:
CanvasRenderingContext2D
(or your browsers version of these)Then the code you have presented will work in html5 canvas (no errors).
Since you are working with pdf.js, your error might be in code you haven't shown us.
Make sure you are feeding pdf.js a valid context
This alert should be
CanvasRenderingContext2D
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.Check the position of your script. I have included it in the
<head>
section so obviously, it tried to findcanvas
element even before letting it appended to the DOM. Thus givingundefined
ornull
error.Some ways to check for errors:
Firstly, you should check for null:
Secondly, make sure you have an element
canvas1
- if it exists thenc
should not benull
; 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.Your code works as far as I can tell (just added the following HTML):
http://jsfiddle.net/qBHRg/