Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

My code is simple, but I have a problem getting the mouse cursor position within the canvas.

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.

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?

here is my code:

 <!doctype html />
<html><head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
  $(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);
    }
   );
  }
  );    
  </script>
  </head>  <body bgcolor="#000000"> <a href="http://jquery.com/">jQuery</a><canvas id="flip" width="500" height="500">
  This text is displayed if your browser does not support HTML5 Canvas.</canvas> </body></html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
662 views
Welcome To Ask or Share your Answers For Others

1 Answer

I see plenty of question on this subject and all propose to browse DOM or use offsetX and offsetY, which are not always set right.

You should use the function: canvas.getBoundingClientRect() from the canvas API.

  function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
      x: evt.clientX - rect.left,
      y: evt.clientY - rect.top
    };
  }

  canvas.addEventListener('mousemove', function(evt) {
    var mousePos = getMousePos(canvas, evt);
    console.log('Mouse position: ' + mousePos.x + ',' + mousePos.y);
  }, false);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...