canvas getContext("2d") returns null

For others who hit this page while searching for getContext returning null, it can happen if you have already requested a different type of context.

For example:

var canvas = ...;
var ctx2d = canvas.getContext('2d');
var ctx3d = canvas.getContext('webgl'); // will always be null

The same is equally true if you reverse the order of calls.


When you do this:

window.onload = init();

the function init() will be executed immediately (what causes the error, because getContext() gets called too early, i.e. before the DOM is loaded), and the return value of init() will be stored to window.onload.

So you want to actually do this:

window.onload = init;

Note the missing ().


This has nothing to do with actual question, but since this question is first result when googling getContex("2d") null I'm adding the solution to problem I had:

Make sure that you use getContext("2d") and not getContext("2D") - notice the lower-case d.