Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
45
rated 0 times [  46] [ 1]  / answers: 1 / hits: 19286  / 12 Years ago, thu, july 5, 2012, 12:00:00

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.


More From » html

 Answers
36

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.
});

[#84438] Wednesday, July 4, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cameron

Total Points: 591
Total Questions: 112
Total Answers: 88

Location: Botswana
Member since Sat, Jan 7, 2023
1 Year ago
cameron questions
;