简体   繁体   English

如何考虑多边形的角

[英]How to consider polygon's corners

I have a canvas code which render polygon shapes. 我有一个渲染多边形形状的画布代码。 I can drag a figure and move it to another place. 我可以拖动一个图并将其移动到另一个地方。 I have move event functions which change the color of the nearest polygons and the draggable polygon. 我有move事件函数,可以更改最近的多边形和可拖动多边形的颜色。 The problem is that I don't know how to make them change their color only when I touching a corner of a figure with my draggable figure. 问题是,仅当我用可拖动的图形触摸图形的一个角时,我才知道如何使它们更改颜色。 I did what I did considering only width and height of a figure so when I drag a figure near the others some of them change their colors when I even don't touch them. 我所做的工作仅考虑图形的widthheight ,因此当我将图形拖到其他图形附近时,其中一些甚至在不触摸它们的情况下也会更改其颜色。 So I should somehow consider their corners ... It's just too complicated to me. 所以我应该以某种方式考虑他们的困境...对我来说太复杂了。

There are relatively much code so I did codepen where you can see what I'm talking about. 有相对多的代码,所以我做了codepen ,您可以在其中看到我在说什么。

PS: only javascript's API allowed. PS:仅允许使用JavaScript的API。

There are many different ways to do hit detection, depending on what you want to detect, how efficiently you want to detect it etc. The link below gives some nice solutions to finding points inside arbitrary polygons by looking at the relationship between the point in question and any y axis intercepts. 根据您要检测的内容,检测效率的高低等多种方法来进行命中检测。下面的链接提供了一些不错的解决方案,可以通过查看相关点之间的关系来查找任意多边形内的点和任何y轴截距。

http://alienryderflex.com/polygon/ http://alienryderflex.com/polygon/

By comparing the given point to the y intercepts, the counts on either side can be used to determine if there is a hit. 通过将给定点与y截距进行比较,可以使用任一侧的计数来确定是否有命中。

y拦截关系

This is solved using a function like the one below, providing an array of x and y coordinates of the polygons vertices, as well as the x and y of the test point. 使用下面的函数可以解决此问题,该函数提供了多边形顶点的x和y坐标数组以及测试点的x和y坐标。

function pointInPolygon(xs, ys, x, y) {

  var j = xs.length - 1
  var oddNodes = false

  for (var i=0; i<xs.length; i++) {
    if ((ys[i] < y && ys[j] >= y ||
         ys[j] < y && ys[i] >= y)
    &&  (xs[i] <= x || xs[j] <= x)) {
      oddNodes ^= (xs[i] + (y - ys[i]) / (ys[j] - ys[i]) * (xs[j] - xs[i]) < x)
    }
    j=i
  }

  return oddNodes
}

I have created a fiddle that shows this in action (clicking on the poly will change its colour). 我创建了一个小提琴来显示实际效果(单击多边形将更改其颜色)。

https://jsfiddle.net/95k3t26q/19/ https://jsfiddle.net/95k3t26q/19/

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

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