1,105,625 Community Members

Javascript with HTML5 canvas help

Member Avatar
wballinger
Newbie Poster
3 posts since Nov 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I've been trying out the HTML5 <canvas> element, and cannot get it to work. here is my code:

<html>
<head>
 <script type="text/javascript" >
    var canvas=document.getElementById("canvas");
    var context=canvas.getContext('2d')
    context.fillRect(100,100,300,300);
</script>
</head>
<body>
  <canvas width="500" height="500" id="canvas" />
</body>
</html>

The canvas is there (I confirmed this), but nothing is on it. A javascript editor gives me this error:
Uncaught TypeError: Cannot call method 'getContext' of null

Does anyone know why?

Member Avatar
scrappedcola
Posting Whiz in Training
219 posts since Dec 2009
Reputation Points: 11 [?]
Q&As Helped to Solve: 45 [?]
Skill Endorsements: 0 [?]
 
0
 

You need to wrap your drawing functionality in a function that gets called on load. The js is running before the canvas object is on the screen.Here is the tutorial code on the mozilla mdc site:

<html>
 <head>
  <script type="application/javascript">
function draw() {
 var canvas = document.getElementById("canvas");
 var ctx = canvas.getContext("2d");

 ctx.fillStyle = "rgb(200,0,0)";
 ctx.fillRect (10, 10, 55, 50);

 ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
 ctx.fillRect (30, 30, 55, 50);
}
  </script>
 </head>
 <body onload="draw()">
   <canvas id="canvas" width="300" height="300"></canvas>
 </body>
</html>
Question Answered as of 3 Years Ago by scrappedcola
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: