Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'getContext' of null, using canvas

I get the error Uncaught TypeError: Cannot read property 'getContext' of null and the important parts in files are... I am wondering since game.js is in a directory below, it cannot find canvas? What should I do?

./index.html:

<canvas id="canvas" width="640" height="480"></canvas> 

./javascript/game.js:

var Grid = function(width, height) {         ...         this.draw = function() {         var canvas = document.getElementById("canvas");         if(canvas.getContext) {             var context = canvas.getContext("2d");             for(var i = 0; i < width; i++) {                 for(var j = 0; j < height; j++) {                     if(isLive(i, j)) {                         context.fillStyle = "lightblue";                     }                     else {                         context.fillStyle = "yellowgreen";                     }                     context.fillRect(i*15, j*15, 14, 14);                 }             }         }     } } 
like image 493
Kobi Avatar asked Apr 24 '12 04:04

Kobi


People also ask

What is getContext in canvas?

getContext() method returns a drawing context on the canvas, or null if the context identifier is not supported, or the canvas has already been set to a different context mode.

What is getContext return?

getContext(): It returns the Context which is linked to the Activity from which it is called. This is useful when we want to call the Context from only the current running activity.

What does Cannot read property of undefined mean?

The "Cannot read properties of undefined" error occurs when trying to access a property on an undefined value. You often get undefined values when: accessing a property that does not exist on an object. accessing an index that is not present in an array.

What does getContext 2D?

The getContext() function is the function that you use to get access to the canvas tags 2D drawing functions. As of April 2014, there are two types of context that are available to you: 2d and webgl . These provide you with the API that you use to draw on the canvas.


1 Answers

I guess the problem is your js runs before the html is loaded.

If you are using jquery, you can use the document ready function to wrap your code:

$(function() {     var Grid = function(width, height) {         // codes...     } }); 

Or simply put your js after the <canvas>.

like image 61
C. Leung Avatar answered Sep 23 '22 15:09

C. Leung