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();
}
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();
}
Share
Improve this question
asked Mar 19, 2014 at 13:34
Aditya.MAditya.M
351 gold badge1 silver badge7 bronze badges
2
-
4
Do you have an element with the ID
canvas1
? The error strongly suggests you don't! – adeneo Commented Mar 19, 2014 at 13:36 - you also will have the same error if canvas1 is defined below the script tag that is using it – async5 Commented Sep 18, 2017 at 15:24
6 Answers
Reset to default 5Firstly, 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.
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 find canvas
element even before letting it appended to the DOM. Thus giving undefined
or null
error.
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"/>
http://jsfiddle/qBHRg/
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);
Touched up if it's stumbled upon recently.
// Canvas class to contain info about element and canvas
// and convenient API for drawing
var Canvas = function (id) {
this.element = document.getElementById('my-canvas');
// if canvas element doesn't exist...
if (!this.element) {
throw new Exception('Canvas $id not found.'.replace('$id', id));
}
// if the getContext method doesn't exist (old browser)
if (!this.element.getContext) {
throw new Exception('Canvas $id cannot load contexts.'.replace('$id', id));
}
this.context2d = this.element.getContext('2d');
// if this particular context isn't supported
if (!this.context2d) {
throw new Exception('Canvas $id cannot load 2D context.'.replace('$id', id));
}
};
// draw a line through each of the given points
Canvas.prototype.drawLine = function (points) {
for (var i = 0, l = points.length; i < l; i++) {
var point = points[i];
// if it's the first point, start a path
// otherwise, continue from the previous point
if (i === 0) {
this.context2d.beginPath();
this.context2d.moveTo(point[0], point[1]);
} else {
this.context2d.lineTo(point[0], point[1]);
}
}
this.context2d.stroke();
};
// create a reference point for our Canvas instance
var myCanvas;
// initialize our Canvas instance on page load
function initCanvas() {
try {
myCanvas = new Canvas('my-canvas');
// draw a diagonal line from the top left to the bottom right
// use actual width and height, not CSS properties,
// unless you want blurred content
myCanvas.drawLine([
[0, 0],
[myCanvas.element.width, myCanvas.element.height]
]);
}
catch(exc) {
window.alert(exc);
}
}
document.addEventListener('DOMContentLoaded', initCanvas, false);