Javascript 在画布中使用javascript获取鼠标位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4848310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:24:16  来源:igfitidea点击:

getting mouse position with javascript within canvas

javascripthtmlcanvas

提问by Bill Yan

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.

我正在学习 jquery 和 html5 画布。我想要做的只是一个简单的 html5 绘图示例。当鼠标移动时,我会在鼠标下方绘制红色方块。

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.

现在,我正在使用 x=event.offsetX; 获取鼠标位置。这在 chrome 中非常有效,但是当涉及到 Firefox 时,它不起作用。我将代码更改为 x=event.layerX。但似乎 layerX 是我的鼠标相对于网页的位置,而不是画布的位置。因为我总是看到一个偏移。

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?

我有两个问题,第一,在 Firefox 下获得正确鼠标位置的正确做法是什么。其次,我如何编写适用于 ie、firefox、chrome、safari 和 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>

采纳答案by Caio

enter image description here

在此处输入图片说明

<!DOCTYPE html>

<html>
    <head>
        <meta charset = "utf-8">

        <script>
            Element.prototype.leftTopScreen = function () {
                var x = this.offsetLeft;
                var y = this.offsetTop;

                var element = this.offsetParent;

                while (element !== null) {
                    x = parseInt (x) + parseInt (element.offsetLeft);
                    y = parseInt (y) + parseInt (element.offsetTop);

                    element = element.offsetParent;
                }

                return new Array (x, y);
            }

            document.addEventListener ("DOMContentLoaded", function () {
                var flip = document.getElementById ("flip");

                var xy = flip.leftTopScreen ();

                var context = flip.getContext ("2d");

                context.fillStyle = "rgb(255,255,255)";   
                context.fillRect (0, 0, 500, 500);

                flip.addEventListener ("mousemove", function (event) {
                    var x = event.clientX;
                    var y = event.clientY;

                    context.fillStyle = "rgb(255, 0, 0)";  
                    context.fillRect (x - xy[0], y - xy[1], 5, 5);
                });
            });    
        </script>

        <style>
            #flip {
                border: 1px solid black;
                display: inline-block;

            }

            body {
                text-align: center;
            }
        </style>
    </head>

    <body>
        <canvas id = "flip" width = "500" height = "500">This text is displayed if your browser does not support HTML5 Canvas.</canvas>
    </body>
</html>

You don't have to worry about compatibility, only IE (prior 9) does not support canvas natively.

您不必担心兼容性,只有 IE(之前 9)本身不支持画布。

回答by AxFab

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.

我看到很多关于这个主题的问题,都建议浏览 DOM 或使用 offsetX 和 offsetY,但它们并不总是正确设置。

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

您应该使用画布 API 中的函数:canvas.getBoundingClientRect()。

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

回答by Olical

You will need a custom function to work out where the element is and then work out where the mouse is within that element. Here is an example. It uses this function from quirks mode and my JavaScript library which should not be difficult to translate into jQuery.

您将需要一个自定义函数来计算元素的位置,然后计算鼠标在该元素中的位置。这是一个例子。它使用了来自 quirks 模式的这个函数和我的 JavaScript 库,应该不难翻译成 jQuery。

function findPos(obj) {
    var curleft = curtop = 0;

    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);

        return [curleft, curtop];
    }
}

EDIT

编辑

This will not work in IE due to it not supporting pageX. You will have to pass the event object through a function like thisto correct that. But as 2x2p1p said, canvas is not supported by any Internet Explorer below version 9.

这在 IE 中不起作用,因为它不支持 pageX。你必须通过一个函数来传递事件对象像这样纠正。但正如 2x2p1p 所说,版本 9 以下的任何 Internet Explorer 都不支持画布。