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.
Solution 4:
Your code works as far as I can tell (just added the following HTML):
<button onclick="abc()">button</button>
<canvas id="canvas1" height="300" width="300"/>
Solution 5:
Assuming your alerts report that you have valid references to your canvas and context:
Alert#1: HTMLCanvasElement
and
Alert#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
// test if the context you're feeding pdf.js is valid
alert(ctx);
// feed pdf.js the context
var myPDFContext = {
canvasContext: ctx,
viewport: viewport
};
page.render(myPDFContext);
Post a Comment for "Cannot Read Property 'getContext' Of Null"