www.webdeveloper.com
Results 1 to 3 of 3

Thread: Can't get my canvas to work propebly

  1. #1
    Join Date
    Jun 2014
    Posts
    2

    Question Can't get my canvas to work propebly

    I cant get this code to work, I see the yellow canvas but in the javascript nothing is working.
    Can anyone see what I am doing wrong?


    <!DOCTYPE html>

    <html>
    <head>
    <script>

    var canvas = document.getElementById("mainCanvas");

    var context = canvas.getContext("2d");


    context.fillStyle("green");
    context.fillRect(100,100,20,20);


    </script>
    <style>
    #mainCanvas{
    background-color: yellow;
    }
    </style>
    </head>
    <body>

    <canvas id = "mainCanvas" width = "500" height = "400" >

    Canvas is not working


    </canvas>

    </body>


    </html>

    HTML Code:
    
    <!DOCTYPE html>
    
    <html>
    <head>
     <script>
    
    var canvas = document.getElementById("mainCanvas");
    
    var context = canvas.getContext("2d");
    
    
    context.fillStyle("green");
    context.fillRect(100,100,20,20);
    
    
     </script>
    <style>
    #mainCanvas{
      background-color: yellow;
    }
    </style>
    </head>
    <body>
    
    <canvas id = "mainCanvas" width = "500" height = "400" >
    
    Canvas is not working
    
    
    </canvas>
    
    </body>
    
    
    </html>
    

  2. #2
    Join Date
    May 2014
    Posts
    900
    Your code order is the problem... you are trying to getElementById at a point at which the DOM (document object model) is incomplete, your canvas#mainCanvas doesn't even exist yet. You'll need to move your script AFTER the CANVAS element in the markup. Basically until the markup for an element has 'gone by' you can't access the element from scripting.

    Generally speaking this is why a lot of developers nowadays prefer to put all their scripts right before </body> instead of in <head> or even in the middle of the markup; you can manipulate the DOM at that point without waiting for "onload"

    Really sloppy scripts use the onload event for doing these sorts of things... typically for no good reason other than copypasta and developer ignorance.
    Java is to JavaScript as Ham is to Hamburger.

  3. #3
    Join Date
    Jun 2014
    Posts
    2
    Thanks Man, from now on I will allways put the script tag in th bottom of the body tag

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles