简体   繁体   中英

HTML5 Canvas not working in external JavaScript file

I have written this code in JavaScript and works perfectly fine when I include it on 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 place it in an external JavaScript file, it won't work! In the head of the index page, I have declared this:

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

And I save this functionality.js file in the JavaScript directory, I've tried doing other JS functions in this file to check the index page and the JS are connected and they are...The answer is probably staring me in the face but for some reason I cannot see it!

Any help is much appreciated, thank you.

EDIT: I've been using Firebug and it is giving me no errors, when I use the code on the index page, I am seeing the shape I want yet when using the external JS file I am just seeing a big black rectangle.

the reason for this is that the script is being run before the canvas element is rendered.

To fix it, add this in your external file.

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

or with jquery

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

Within functionality.js , try wrapping your code in

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

so that it won't execute until after the page has loaded.

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

Add the script tag in the same place it works with the inline code. JavaScript does not have to live in the head and some developers will recommend it should always be the last thing in the body.

Other solution is to run the script on document ready or window onload.

不要放在头脑中,当你把代码放在头部时,它会在页面中没有canvas元素时运行代码。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM