检测鼠标是否悬停在画布内的对象上

7

我已经在canvas元素内创建了一条线。我正在寻找最简单的方法来检测鼠标位置是否在位于canvas内的该线内。

我使用了这个函数来查看鼠标在canvas内的位置,但我很困惑应该如何继续。

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

我也看了这个主题Fabricjs检测鼠标在对象路径上的位置,但它只检测鼠标是否在画布内,而不是在对象内。
我创建的线是较小的线段之一,相互连接。
 for (var i = 0; i < 140 ; i++) {

                ctx.beginPath();

                ctx.moveTo(x[i],y[i]);
                ctx.quadraticCurveTo(x[i],50,x[i+1],y[i+1]);
                ctx.lineWidth = 40;

                ctx.strokeStyle = 'white';
                ctx.lineCap = 'round';
                ctx.stroke();

            }

其中x[i]和y[i]是我想要的具有坐标的数组。

希望我的问题很清晰,尽管我不太熟悉JavaScript。

谢谢 Dimitra


https://developer.mozilla.org/en-US/docs/Web/Reference/Events/mouseover - thatidiotguy
2个回答

17

演示:http://jsfiddle.net/m1erickson/Cw4ZN/

enter image description hereenter image description here

您需要掌握以下概念,以检查鼠标是否在线段内:

  • 定义线段的起点和终点

  • 监听鼠标事件

  • 在鼠标移动时,检查鼠标是否在指定距离内的线段上

以下是带注释的示例代码,供您学习参考。

$(function() {

  // canvas related variables
  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");
  var $canvas = $("#canvas");
  var canvasOffset = $canvas.offset();
  var offsetX = canvasOffset.left;
  var offsetY = canvasOffset.top;

  // dom element to indicate if mouse is inside/outside line
  var $hit = $("#hit");

  // determine how close the mouse must be to the line
  // for the mouse to be inside the line
  var tolerance = 5;

  // define the starting & ending points of the line
  var line = {
    x0: 50,
    y0: 50,
    x1: 100,
    y1: 100
  };

  // set the fillstyle of the canvas
  ctx.fillStyle = "red";

  // draw the line for the first time
  draw(line);

  // function to draw the line
  // and optionally draw a dot when the mouse is inside
  function draw(line, mouseX, mouseY, lineX, lineY) {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    ctx.moveTo(line.x0, line.y0);
    ctx.lineTo(line.x1, line.y1);
    ctx.stroke();
    if (mouseX && lineX) {
      ctx.beginPath();
      ctx.arc(lineX, lineY, tolerance, 0, Math.PI * 2);
      ctx.closePath();
      ctx.fill();
    }
  }

  // calculate the point on the line that's 
  // nearest to the mouse position
  function linepointNearestMouse(line, x, y) {
    //
    lerp = function(a, b, x) {
      return (a + x * (b - a));
    };
    var dx = line.x1 - line.x0;
    var dy = line.y1 - line.y0;
    var t = ((x - line.x0) * dx + (y - line.y0) * dy) / (dx * dx + dy * dy);
    var lineX = lerp(line.x0, line.x1, t);
    var lineY = lerp(line.y0, line.y1, t);
    return ({
      x: lineX,
      y: lineY
    });
  };

  // handle mousemove events
  // calculate how close the mouse is to the line
  // if that distance is less than tolerance then
  // display a dot on the line
  function handleMousemove(e) {
    e.preventDefault();
    e.stopPropagation();
    mouseX = parseInt(e.clientX - offsetX);
    mouseY = parseInt(e.clientY - offsetY);
    if (mouseX < line.x0 || mouseX > line.x1) {
      $hit.text("Outside");
      draw(line);
      return;
    }
    var linepoint = linepointNearestMouse(line, mouseX, mouseY);
    var dx = mouseX - linepoint.x;
    var dy = mouseY - linepoint.y;
    var distance = Math.abs(Math.sqrt(dx * dx + dy * dy));
    if (distance < tolerance) {
      $hit.text("Inside the line");
      draw(line, mouseX, mouseY, linepoint.x, linepoint.y);
    } else {
      $hit.text("Outside");
      draw(line);
    }
  }

  // tell the browser to call handleMousedown
  // whenever the mouse moves
  $("#canvas").mousemove(function(e) {
    handleMousemove(e);
  });

}); // end $(function(){});
body {
  background-color: ivory;
}

canvas {
  border: 1px solid red;
}
<!doctype html>
<html>

<head>
  <link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />
  <!-- reset css -->
  <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

</head>

<body>
  <h2 id="hit">Move mouse near line</h2>
  <canvas id="canvas" width=300 height=300></canvas>
</body>

</html>

关于命中测试路径:

如果您使用路径命令创建路径,则可以使用context.isPointInPath(mouseX,mouseY)检查鼠标是否在路径内。但是,由于理论上线条的宽度为零,因此context.isPointInPath无法很好地处理线条。


非常感谢您的回答。我想知道是否可以将此应用于曲线(它是多条线的一部分)。我将编辑我的问题,以便清楚地解释到目前为止我如何创建这条线。 - Dimitra Micha
1
如果你的路径是封闭的,那么你可以使用 isPointInPath 来检查鼠标是否在你的封闭路径内。现代浏览器支持新的 isPointInStroke,它可以测试线条路径。否则,你将不得不像我的回答一样手动完成。另一种方法是获取画布的所有像素数据,然后检查鼠标下面的像素是否是不透明的(在线上)或者是透明的(不在线上)。 - markE
不,我的路径并没有关闭。所以,我猜我不能使用'isPointInStroke'。我找到了这个链接http://neimke.blogspot.nl/2011/03/detect-when-object-is-clicked-on-html.html,也许有一个更简单的解决方案适用于我正在寻找的内容。 - Dimitra Micha
1
这里有一个示例,可以从画布中读取像素。您可以测试此像素数组以查看鼠标是否悬停在不透明像素上(在线的某个部分):http://jsfiddle.net/m1erickson/K2PDZ/ - markE
如果您的形状可以简化为矩形或圆形(或矩形和圆形的组合),那么您可以轻松使用数学来进行命中测试,以确定鼠标是否在矩形或圆形内部。 - markE
显示剩余4条评论

0
this.element.addEventListener("mouseenter", (event) => {});

鼠标悬停在一个 div 上

this.element.addEventListener("mouseleave", (event) => {});

鼠标离开 div


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接