Search code examples
javascripthtmlcanvasdetectionimagemap

HTML/JS detecting areas on an image


On web (actually webview in mobile development), I have an image of a basketball court. I need to detect the click(touch) of the area on the court image, whether it is within the 3 point line or outside of it. What is the simplest way of achieving this? Old school image map? SVG? Canvas tag?


Solution

  • This is easiest done on a <canvas> element using well known frameworks like Kinetic and Fabric.

    You would load the image in the bottom layer, then apply a 3pt layer over the whole image. On top of the 3pt layer is a 2pt layer in the form of an arc. The layering would look like this, from top to bottom:

    - 2pt "arc" layer on either side  |
    - 3pt "full court" layer          |  Click propagation
    - court image                     V
    

    So when the player touches inside the 2pt arc layer, you know it's 2pt. When the player touches outside the arc, it's the 3pt layer that catches the touch. Additionally, frameworks might allow a propagation to underlying layers. You must prevent that one.