canvas getContext(“2d”) returns null

ε祈祈猫儿з 提交于 2019-11-27 21:53:59

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

Duba911

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!