简体   繁体   中英

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. 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. 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.

PS: only javascript's API allowed.

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.

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拦截关系

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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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