Skip to content Skip to sidebar Skip to footer

Html5 Canvas And Javascript Document.getelementbyid() Returns Null

I'm trying to use html5 canvas and when I do var c=document.getElementById('myCanvas'); var ctx=c.getContext('2d'); ctx.fillStyle='#FF0000'; ctx.fillRect(0,0,150,7

Solution 1:

Chances are your script is run before your DOM is ready and window has loaded, try for instance:

window.onLoad=function(){
    var c=document.getElementById('myCanvas');
    var ctx=c.getContext('2d');
    ctx.fillStyle="#FF0000";
    ctx.fillRect(0,0,150,75);
};

Solution 2:

Try to insert your script before the closing body tag.

Like:

...
    <scriptsrc="game.js"></script></body>
...

Solution 3:

May you try to get it before DOM was loaded? Try to call your code inside this block:

window.onload = function() {
    var c=document.getElementById('myCanvas');
    var ctx=c.getContext('2d');
    ctx.fillStyle="#FF0000";
    ctx.fillRect(0,0,150,75);
}; 

Solution 4:

If you want to access DOM Element through javascript, make sure your java script code should triggered after DOM is loaded, use document.onload or window.onload callbacks to trigger your javascript code..

Enjoy Coding..

Post a Comment for "Html5 Canvas And Javascript Document.getelementbyid() Returns Null"