JavaScript + Canvas

3

Hello,

People I'm studying canvas with HTML5 so that I came up with the following problem, when I import the external JavaScript file inside the "head" tag it does not recognize. Only when I put dentor of the body.

var canvas = document.getElementById('myCanvas');

if (canvas.getContext) {
  var context = canvas.getContext("2d");
  context.fillStyle = "rgb(200,0,0)";
  context.fillRect(10, 10, 55, 50);

  context.fillStyle = "rgba(0, 0, 200, 0.5)";
  context.fillRect(30, 30, 55, 50);
}

When I post:

<!-- JavaScript externo -->  
<script type="text/javascript" src="js/script.js"></script>

Inside the head tag it does not work, just at the end of the body

    
asked by anonymous 10.02.2017 / 08:23

1 answer

6

This happens because when the browser reads head and runs the script, document.body does not yet exist. That is document.getElementById('myCanvas'); can only run after the browser has read this HTML.

You can leave it in head but within a callback to only run when the DOM is ready, or how are you doing in body .

To leave in head :

window.onload = function(){
    var canvas = document.getElementById('myCanvas');
    if (canvas.getContext) {
      var context = canvas.getContext("2d");
      context.fillStyle = "rgb(200,0,0)";
      context.fillRect(10, 10, 55, 50);

      context.fillStyle = "rgba(0, 0, 200, 0.5)";
      context.fillRect(30, 30, 55, 50);
    }
}
    
10.02.2017 / 10:15