title: getting mouse position with javascript within canvas
body: <p>I'm studying jquery and html5 canvas. All I want to do is a simple html5 drawing example. When the mouse move, I draw red squares under my mouse.</p>
  
  <p>My code is simple, but I have a problem getting the mouse cursor position within the canvas.</p>
  
  <p>Right now, I am using x=event.offsetX; to get the mouse position. This works very well in chrome, however when it comes to firefox, it doesn't work. I changed the code to x=event.layerX. but it seems that layerX is the position of my mouse relative to the web page, not the position of the canvas. because I always see an offset.</p>
  
  <p>I have two questions, first, what is the right thing to do to get the correct mouse position under firefox. second, how can i write a code that works for ie, firefox, chrome, safari and opera?</p>
  
  <p>here is my code:</p>
  
  <pre><code> &lt;!doctype html /&gt;
  &lt;html&gt;&lt;head&gt;
  &lt;script type="text/javascript" src="jquery.js"&gt;&lt;/script&gt;
  &lt;script type="text/javascript"&gt;
    $(document).ready(
   function(){
  
  var flip = document.getElementById('flip');
      var context = flip.getContext('2d');   
  context.fillStyle = "rgb(255,255,255)";   
  context.fillRect(0, 0, 500, 500);
  
        $("a").click(function(event){alert("Thanks for visiting!");});
     $("#flip").mousemove(function(event){
        var x, y;
  
  
      x = event.layerX;
      y = event.layerY;
  
  
      //alert("mouse pos"+event.layerX );
      var flip = document.getElementById('flip');
      var context = flip.getContext('2d');   
  context.fillStyle = "rgb(255,0,0)";   
  context.fillRect(x, y, 5, 5);
      }
     );
    }
    );    
    &lt;/script&gt;
    &lt;/head&gt;  &lt;body bgcolor="#000000"&gt; &lt;a href="http://jquery.com/"&gt;jQuery&lt;/a&gt;&lt;canvas id="flip" width="500" height="500"&gt;
    This text is displayed if your browser does not support HTML5 Canvas.&lt;/canvas&gt; &lt;/body&gt;&lt;/html&gt;
  </code></pre>