[javascript] 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);
                }
            }
        }
    }
}

This question is related to javascript html canvas

The answer is


Write code in this manner ...

<canvas id="canvas" width="640" height="480"></canvas>
<script>
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);
                }
            }
        }
    }
 }

First write canvas tag and then write script tag. And write script tag in body.


You should put javascript tag in your html file. because browser load your webpage according to html flow, you should put your javascript file<script src="javascript/game.js"> after the <canvas>element tag. otherwise,if you put your javascript in the header of html.Browser load script first but it doesn't find the canvas. So your canvas doesn't work.


Put your JavaScript code after your tag <canvas></canvas>


You don't have to include JQuery.

In the index.html:
<canvas id="canvas" width="640" height="480"></canvas><script src="javascript/game.js"> This should work without JQuery...

Edit: You should put the script tag IN the body tag...


I assume you have your JS file declared inside the <head> tag so it keeps it consistent, like standard, then in your JS make sure the canvas initialization is after the page is loaded:

window.onload = function () {
    var myCanvas = document.getElementById('canvas');
    var ctx = myCanvas.getContext('2d');
}

There is no need to use jQuery just to initialize a canvas, it's very evident most of the programmers all around the world use it unnecessarily and the accepted answer is a probe of that.


You just need to put<script src='./javascript/game.js'></script> after your <canvas>. Because the browser don't find your javascript file before the canvas


This might seem like overkill, but if in another case you were trying to load a canvas from js (like I am doing), you could use a setInterval function and an if statement to constantly check if the canvas has loaded.

//set up the interval
var thisInterval = setInterval(function{
  //this if statment checks if the id "thisCanvas" is linked to something
  if(document.getElementById("thisCanvas") != null){
    //do what you want


    //clearInterval() will remove the interval if you have given your interval a name.
    clearInterval(thisInterval)
  }
//the 500 means that you will loop through this every 500 milliseconds (1/2 a second)
},500)

(In this example the canvas I am trying to load has an id of "thisCanvas")


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to canvas

How to make canvas responsive How to fill the whole canvas with specific color? Use HTML5 to resize an image before upload Convert canvas to PDF Scaling an image to fit on canvas Split string in JavaScript and detect line break Get distance between two points in canvas canvas.toDataURL() SecurityError Converting Chart.js canvas chart to image using .toDataUrl() results in blank image Chart.js canvas resize