1

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,75);

and here is the html

    <!DOCTYPE html>
    <html>
    <head>
    <script type="text/javascript" src="game.js"></script>
    </head>
    <body>
    <canvas id="myCanvas" width="512" height="480" style="border:1px solid #000000;">
    </canvas>
    </body>
    </html>

I have no clue what's wrong

lilwayne1556
  • 27
  • 1
  • 1
  • 6

4 Answers4

6

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);
};
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
1

Try to insert your script before the closing body tag.

Like:

...
    <script src="game.js"></script>
</body>
...
Mohammad Areeb Siddiqui
  • 9,795
  • 14
  • 71
  • 113
0

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);
}; 
XiM
  • 396
  • 3
  • 15
0

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

Scarecrow
  • 4,057
  • 3
  • 30
  • 56