HTML5 Canvas not working in external JavaScript file

I wrote this code in JavaScript and works great when I include it in my index.html page:

<canvas id="bannerCanvas" width="960" height="200"> Your browser does not support the canvas element. </canvas> <script type="text/javascript"> var canvas = document.getElementById("bannerCanvas"); var context = canvas.getContext("2d"); context.beginPath(); context.moveTo(25,25); context.lineTo(355,55); context.lineTo(355,125); context.lineTo(25,125); context.moveTo(465,25); context.fill(); }; </script> 

... however, when I put it in an external JavaScript file, it will not work! In the header of the index page, I stated the following:

  <script type="text/javascript" src="JavaScript/functionality.js"> </script> 

And I save this functions.js file in the JavaScript directory, I tried to do other JS functions in this file to check the index page, and the JS are connected, and they ... The answer is probably a person, but somehow I don’t see his!

Any help is much appreciated, thanks.

EDIT: I used Firebug and it does not give me any errors, when I use the code on the index page, I see the form that I want even when using an external JS file. I just see a big black rectangle.

+4
source share
4 answers

the reason for this is because the script is executed before the canvas element is rendered.

To fix this, add this to your external file.

 document.addEventListener('DOMContentLoaded',domloaded,false); function domloaded(){ // your code here. } 

or using jquery

 $(function(){ // your code here. }); 
+11
source

Inside functionality.js try wrapping your code in

 window.onload = function() { // code here } 

so that it does not run until the page loads.

+3
source

If it is in the head, you load it before rendering the canvas element. Look at the JavaScript console and you will see a Null or undefined error.

Add the script tag in the same place that it works with inline code. JavaScript should not live in the head, and some developers recommend that it always be the last in the body.

Another solution is to run the script on the finished or finished document.

+2
source

Do not put in the head. When you put the code in your head, it runs the code when there is no canvas element on the page yet.

+1
source

All Articles