I\'ve tried this a few different ways, but I keep getting stuck with the same error. I\'ve loaded an image to canvas before, but since I updated Safari a few days ago, I\'m
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 ()
.
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.
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.
Just put your JavaScript at the end of the page it will ... put an end to your problems... i tried everything but this the most logical and simple solution.. as that JS will run only after the other part(ie the upper page) has loaded.. hope this help
Make sure javascript runs after the canvas HTML element
This is bad
<body>
<script src="Canvas.js"></script>
<canvas id="canvas"></canvas>
</body>
This is good
<body>
<canvas id="canvas"></canvas>
<script src="Canvas.js"></script>'
</body>
This is basically how I fixed my problem