Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript check Mouse clicked inside the Circle or Polygon

Tags:

javascript

Any one know how to check that wheter a mouse is clicked inside the circle or polygon. My problem is I want to check that if mouse has been clciked inside the circle or polygon. circle or polygon coordinates has been stored inside an array. Any help is really appreciated

like image 847
Dheeraj Avatar asked Feb 06 '10 09:02

Dheeraj


1 Answers

As suggested by some other answers, I followed some links and found the c code here. Here is the JavaScript translation for finding whether a point is in a polygon

Copyright (c) 1970-2003, Wm. Randolph Franklin

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimers.
  2. Redistributions in binary form must reproduce the above copyright notice in the documentation and/or other materials provided with the distribution.
  3. The name of W. Randolph Franklin may not be used to endorse or promote products derived from this Software without specific prior written permission.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

function pnpoly( nvert, vertx, verty, testx, testy ) {
    var i, j, c = false;
    for( i = 0, j = nvert-1; i < nvert; j = i++ ) {
        if( ( ( verty[i] > testy ) != ( verty[j] > testy ) ) &&
            ( testx < ( vertx[j] - vertx[i] ) * ( testy - verty[i] ) / ( verty[j] - verty[i] ) + vertx[i] ) ) {
                c = !c;
        }
    }
    return c;
}

nvert - Number of vertices in the polygon. Whether to repeat the first vertex at the end is discussed below.
vertx, verty - Arrays containing the x- and y-coordinates of the polygon's vertices.
testx, testy - X- and y-coordinate of the test point.

like image 68
meouw Avatar answered Sep 20 '22 16:09

meouw