0

Is there any algorithm to determine whether the clicked location is inside the unshaped object or not?

I am new at canvas. but, it would be easy to know the mouse coordinates are in the shaped object especially in rectangle. But, what about an unshaped object or sphere/hexagon/octagon etc.?

For example I have a following code. Then how do I implement the logic to determine whether the coordinates of my mouse click is inside the object area or not?

 function drawShape(){
   var canvas = document.getElementById("cnvs");
    var ctx = canvas.getContext("2d");
    
    ctx.beginPath();
    ctx.moveTo(20,0);
    ctx.lineTo(30,10);    
    ctx.lineTo(30,50);
    ctx.lineTo(45,100);
    ctx.lineTo(60,45);
    ctx.lineTo(55,30);
    ctx.lineTo(90,45);
    ctx.lineTo(100,100);
    ctx.lineTo(50,150);
   ctx.lineTo(45,160);
    ctx.lineTo(20,100);
    ctx.lineTo(10,50);
    
    ctx.closePath();
    ctx.fill();
    
    $(canvas).click(function(){
       var canvas = this;
        var event = window.event;
        alert(event.pageX - canvas.offsetLeft);
  });
  }
  drawShape();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<canvas id="cnvs" width="200" height="200">
  
</canvas>
Shell
  • 6,818
  • 11
  • 39
  • 70
  • The easiest way to test if any [x,y] is inside your arbitrary path is to use [context.isPointInPath](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/isPointInPath). It's a bit slower than raw math methods. – markE Oct 23 '16 at 20:14
  • Thanks @markE, your solution seems usefull to me.. let me try it with a simple example. – Shell Oct 24 '16 at 06:32
  • Thanks a lot @markE, It works [fiddle](https://jsfiddle.net/haeakbmq/1/). Can you post this as an answer? So, I will mark my question as resolved. One more question, you said math methods are much faster than this. what is that? – Shell Oct 24 '16 at 08:37

1 Answers1

1

You need to define that logic separately for each shape you might expect.

A circle is the easiest of all, you can just check if the distance between the center of the circle and the mouse coordinates is less than the circle's radius.

There is, however, an algorithm for an arbitrary polygon:

  1. Cast a ray from the point clicked, in any direction.
  2. Check for intersection of the ray with each of the segments of your shape.
  3. Count the number of such intersections. If it's even, then the point lies outside of your shape, if it's odd, then it lies within.
unholybear
  • 191
  • 6