Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
682 views
in Technique[技术] by (71.8m points)

html - getting mouse position with javascript within canvas

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

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

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...