Reputation: 4635
I'm stumling upon a weird problem: The code just wont be able to access the canvas element. Consider this code:
this.canvas = document.getElementById('canvas');
this.context2D = this.canvas.getContext('2d');
Firefox would produce an error say this.canvas is null
. But if I write it like this:
this.canvas = $('#canvas');
this.context2D = this.canvas.getContext('2d');
Firefox would tell getContext is not a method
. I looked into this.canvas
and see an unfamiliar object (no idea where it comes from but it definitely not a canvas).
And this is not exclusive to Firefox, Chrome produce the same result. I'm getting crazy over this.
edit: the entire html is here
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Background test</title>
<script type="text/javascript" src="Scripts/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="Scripts/soundmanager2.js"></script>
<script type="text/javascript" src="Scripts/base.js"></script>
<script type="text/javascript" src="Scripts/Resources.js"></script>
<script type="text/javascript" src="Scripts/Actor.js"></script>
<script type="text/javascript" src="Scripts/Commons.js"></script>
<script type="text/javascript" src="Scripts/Graphics.js"></script>
<script type="text/javascript" src="Scripts/Utils.js"></script>
<script type="text/javascript">
window.onload = function(){
new Commons().startupCommons();
new Graphics().startupGraphics();
}
</script>
<style type="text/css">
body { font-family: Arial,Helvetica,sans-serif;}
canvas {border-style:solid; border-width:5px; border-color:green;}
</style>
</head>
<body>
<canvas id="visualcanvas" width="800" height="600">
<p>
Your browser does not support the canvas element.
</p>
</canvas>
</body>
</html>
I just added window.onload, but the problem persist. this
in the before code refer to the Graphics object, which is call when window.onload
fire.
Upvotes: 1
Views: 2337
Reputation: 943100
What is $? Is it Prototype.js? I'm going to assume it is jQuery.
If you call jQuery(someselector)
then you will get a jQuery object. If there are no elements that match the selector, then it will be a jQuery object with no items in it.
Either way, you can't treat it as a canvas object.
The first set of code doesn't work, probably, because there is no element with the id 'canvas' in the DOM at the time the line of JS is executed. This is most likely because you are running the JS in a script element that appears before the element with the id 'canvas' (and haven't done anything to delay execution, such as calling it via the document ready event) or because you are confusing the id attribute and the tag name.
Upvotes: 4