jQuery- Please explain to me Closure, variable context
<p>Ok so I don't understand why Firefox is saying that the $("#canvas")[0].getContext('2d'); is undefined. I put it out of the function so that all of the function can access it but here the ctx is still undefined.</p>

<pre><code>(function($) {
        // Undefined
     var ctx = $('#canvas')[0].getContext("2d");
     var x = 150;
     var y = 150;
     var dx = 2;
     var dy = 4;
     $(function() {
      setInterval(draw, 10);
     })
     function draw() {
      ctx.clearRect(0,0,300,300);
      ctx.beginPath();
      ctx.arc(x,y,10,0,Math.PI*2,true);
      ctx.closePath();
      ctx.fill();
      x+=dx;
      y+=dy;
     }
    })(jQuery);
</code></pre>

<p>However when I transferred the location of ctx to the unnamed function, the ctx is not undefined:</p>

<pre><code>(function($) {
     var ctx;
     var x = 150;
     var y = 150;
     var dx = 2;
     var dy = 4;
     $(function() {
              //Not Undefined
      ctx = $("#canvas")[0].getContext('2d');
      setInterval(draw, 10);
     })
     function draw() {
      ctx.clearRect(0,0,300,300);
      ctx.beginPath();
      ctx.arc(x,y,10,0,Math.PI*2,true);
      ctx.closePath();
      ctx.fill();
      x+=dx;
      y+=dy;
     }
    })(jQuery);
</code></pre>

<p>Whats wrong with the first code? I mean var ctx is declared on the top. So that would make it a global variable. Hmm the error that I got was $("#canvas")[0] is undefined. Means that it can't access the #canvas.. Why??</p>
