title: using javascript to drag and drop images on html5 canvas
body: <p>I tried following the tutorial suggested in answer to the question at <a href="https://stackoverflow.com/questions/4468940/drag-and-drop-canvas-in-html5">Drag and Drop canvas in HTML5</a> but when I load my page in Firefox, the Firebug console displays an error saying that "canvas is null".</p>
  
  <p>The file it's complaining about is the JS file where I've put the code for user interaction:</p>
  
  <pre><code>var canvas;
  var ctx;
  var x = 75;
  var y = 50;
  var WIDTH = 400;
  var HEIGHT = 300;
  var dragok = false;
  
  function rect(x,y,w,h) {
   ctx.beginPath();
   ctx.rect(x,y,w,h);
   ctx.closePath();
   ctx.fill();
  }
  
  function clear() {
   ctx.clearRect(0, 0, WIDTH, HEIGHT);
  }
  
  function init() {
   canvas = document.getElementById("gameCanvas");
   ctx = canvas.getContext("2d");
   return setInterval(draw, 10);
  }
  
  function draw() {
   clear();
   ctx.fillStyle = "#FAF7F8";
   rect(0,0,WIDTH,HEIGHT);
   ctx.fillStyle = "#444444";
   rect(x - 15, y - 15, 30, 30);
  }
  
  function myMove(e){
   if (dragok){
    x = e.pageX - canvas.offsetLeft;
    y = e.pageY - canvas.offsetTop;
   }
  }
  
  function myDown(e){
   if (e.pageX &lt; x + 15 + canvas.offsetLeft &amp;&amp; e.pageX &gt; x - 15 +
   canvas.offsetLeft &amp;&amp; e.pageY &lt; y + 15 + canvas.offsetTop &amp;&amp;
   e.pageY &gt; y -15 + canvas.offsetTop){
    x = e.pageX - canvas.offsetLeft;
    y = e.pageY - canvas.offsetTop;
    dragok = true;
    canvas.onmousemove = myMove;
   }
  }
  
  function myUp(){
   dragok = false;
   canvas.onmousemove = null; 
  }
  
  init();
  canvas.onmousedown = myDown;
  canvas.onmouseup = myUp;
  </code></pre>
  
  <p>The main error is "canvas is null", and when I expand that, it complains about <code>init()</code> on line 22, <code>interaction.js()</code> on line 57. 
  Line 22 is the line:</p>
  
  <pre><code> ctx = canvas.getContext("2d");
  </code></pre>
  
  <p>and line 57 is the line:</p>
  
  <pre><code>init();
  </code></pre>
  
  <p>Could someone point out to me where I'm going wrong?</p>
  
  <p>Cheers.</p>
  
  <p>The HTML where my canvas is is this:</p>
  
  <pre><code>&lt;canvas id="gameCanvas" width="1000" height="500" style="border:1px solid"&gt;
      Your browser does not support the canvas element.
      &lt;/canvas&gt;
  </code></pre>