We're a community of 1.1M IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,080,608 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Javascript with HTML5 canvas help

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?

2
Contributors
1
Reply
10 Minutes
Discussion Span
2 Years Ago
Last Updated
2
Views
Question
Answered
wballinger
Newbie Poster
3 posts since Nov 2010
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 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>
scrappedcola
Posting Whiz in Training
227 posts since Dec 2009
Reputation Points: 27
Solved Threads: 45
Skill Endorsements: 0
Question Answered as of 2 Years Ago by scrappedcola

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page generated in 0.0555 seconds using 2.66MB