繁体   English   中英

如何检查鼠标 position 是否在 HTML5 Canvas 路径内?

[英]How to check if mouse position is inside HTML5 Canvas path?

我是 HTML5 Canvas 和 Javascript 的新手。 我目前正在研究 HTML5 Canvas 项目(我在这里这里写了一个单独的问题)。

游戏的逻辑非常简单:跟踪鼠标 position,如果鼠标 position 退出蓝色区域,则游戏重置。 用户从级别 1 ( function firstLevel ) 开始。 如果他们的鼠标 position 进入红框区域,他们会前进到下一个级别( return secondLevel() )。 我之前通过比较鼠标的 x 和 y 坐标的大量if语句列表来做到这一点。

我已更正代码以创建全局构造函数 function 我可以在每个级别函数中引用:

function Path(array, color) {
  let path = new Path2D();
  path.moveTo(array[0][0], array[0][1]); 
  for (i = 1; i < array.length; i++) {
    path.lineTo(array[i][0], array[i][1]);
  }
  path.lineTo(array[0][0], array[0][1]);
  return path;
} 

它在关卡函数中的引用如下:

    // In the individual levels, put code that describes the shapes locally
    var big = [[350,200], [900,200], [900,250], [700,250], [600,250], [600,650], [350,650]];
    var blue = Path(big);

    var small = [[900,200], [900,250], [850,250], [850, 200], [900, 200]];
    var red = Path(small);

      // 2. create cursor
      c.beginPath();
      c.rect(mouseX, mouseY, mouseWidth, mouseHeight);
      c.fillStyle = "#928C6F";
      c.fill();

    // Local code that draws shapes:
    c.beginPath()
    c.fillStyle = '#C1EEFF';
    c.fill(blue);

    c.beginPath()
    c.fillStyle = "#FF4000";
    c.fill(red);

我想知道如何检查鼠标 position 以便它可以使用isPointInPath方法运行这些条件语句? 我现在有 Canvas 形状的参考(参考bluered ),所以我希望有一种方法可以检查鼠标的 x 和 y position 是否是形状/路径内的点。

链接到我的项目: https://github.uconn.edu/pages/ssw19002/dmd-3475/final-project/maze-page-1.html

源码: https://github.uconn.edu/ssw19002/dmd-3475/tree/master/final-project

您可以使用鼠标事件的MouseEvent.offsetXMouseEvent.offsetY属性,例如mousemove (当然,您需要将鼠标事件的事件侦听器添加到 canvas 元素。)

然后使用得到的xy偏移值来调用isPointInPath之类的

ctx.isPointInPath(path, x, y)

其中pathfunction Path的返回值。

虽然 MDN 将偏移属性列为“实验性”,但它们似乎至少从 IE9 开始就存在了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM