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?

Recommended Answers

All 2 Replies

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>

I caught an error 'context is not defined' in js for canvas,so what I do for canvas problems>

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.