Javascript + Canvas

Asked

Viewed 113 times

3

Hello,

We are studying canvas with HTML5 so I came up with the following problem, when I import the external Javascript file inside the tag "head" it does not recognize. Only when I put dentor on my 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 put:

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

Inside the tag head it does not work, only at the end of the body(body)

1 answer

6

This is because when the browser reads the head and run the script, the 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 on head but into a callback to only run when the DOM is ready, or as you are doing in the body.

To leave in the 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);
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.