Reputation: 8891
Here is my html:
<canvas id="test" width="400" height="200"></canvas>
here is my javascript:
var canvas_one = document.getElementById("test");
var canvas_context = canvas_one.getContext("2d");
canvas_context.fillRect(50, 25, 150, 100);
I am just experimenting with this and none of the tutorials seem to be working. I am using chrome as my browser fyi.
The original typo was only on here; not in my editor. Sorry about that.
I am getting the error: Uncaught TypeError: Cannot call method 'getContext' of null even with the jsfiddle example.
Ok I figured out what was wrong. Because my javascript was in the head of the html file, it was being loaded before the DOM was completely loaded, So when it tried to do var canvas_one = document.getElementById("test");
it set canvas_one to null. So what I did is just wrap it in jquery like this:
$(document).ready(function(){
var canvas_one = document.getElementById("test");
var canvas_context = canvas_one.getContext("2d");
canvas_context.fillStyle = "rgb(255,0,0)";
canvas_context.fillRect(10, 25, 150, 100);
});
Now it waits for the DOM to load before it reads the javascript and everything works.
Upvotes: 2
Views: 3625
Reputation: 8503
Make sure any code which references the DOM executes only after the DOM is ready. This can be achieved by wrapping everything in a function which is called using window.onload, or by using jQuery or a similar library to do this for you.
Upvotes: 1
Reputation: 1199
The mozilla tutorial is the best one in my opinion, try it.
Correct the following: document.getElementById, you just typed it wrong.
Upvotes: 2
Reputation: 35319
You have a typo for getElementById
, also I suggest setting a fillStyle
as well.
var canvas_one = document.getElementById("test");
var canvas_context = canvas_one.getContext("2d");
canvas_context.fillStyle = "rgb(255,0,0)";
canvas_context.fillRect(10, 25, 150, 100);
Upvotes: 0