2

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
  • 35
  • 1
  • 1
  • 7

6 Answers6

5

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.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
  • 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. – Aditya.M Mar 19 '14 at 14:39
  • If `c` is `null` then you don't have a canvas with `id="canvas1"`. Change it to the ID of your canvas. – Dissident Rage Mar 27 '14 at 14:21
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.

samuelkobe
  • 546
  • 4
  • 16
  • 1
    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. – Slayer Of Whales Jul 16 '21 at 08:33
1

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.

Rajan Verma - Aarvy
  • 1,969
  • 18
  • 20
0

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.net/qBHRg/

Johan
  • 1,016
  • 7
  • 13
0

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);
Dissident Rage
  • 2,610
  • 1
  • 27
  • 33
  • Nothing wrong...I suspect OP has issue somewhere else in his code. +1 to reverse someone else's minuses. – markE Mar 19 '14 at 18:30
0

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);
markE
  • 102,905
  • 11
  • 164
  • 176