canvas getContext(“2d”) returns null

前端 未结 5 2194
天命终不由人
天命终不由人 2020-12-05 17:53

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

相关标签:
5条回答
  • 2020-12-05 18:03

    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 ().

    0 讨论(0)
  • 2020-12-05 18:04

    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.

    0 讨论(0)
  • 2020-12-05 18:20

    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.

    0 讨论(0)
  • 2020-12-05 18:24

    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

    0 讨论(0)
  • 2020-12-05 18:24

    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

    0 讨论(0)
提交回复
热议问题