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); } } } } }
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.
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.
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.
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.
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With