1

Is it possible, using either HTML canvas or Javascript, to click on part of an image and, depending on which part you clicked, it trigger a Javascript event?

So, for example;

If I have an image of a watch and the user clicks on the strap, this triggers a modal with content relating to the strap. Similarly, if they click on one of the watch hands, this triggers a different modal.

Dean Elliott
  • 169
  • 5
  • 12
  • Possible duplicate of [jQuery get mouse position within an element](http://stackoverflow.com/questions/4249648/jquery-get-mouse-position-within-an-element) – Ahmet Emre Kilinc Apr 24 '17 at 11:13
  • You can place your image as css `background-image` property. Then you can add different divs inside your main container. [something like this](http://imgur.com/a/Q70eX). And then add onClick handler to your div – Zhenya Telegin Apr 24 '17 at 11:26
  • @ZhenyaTelegin That would work for the larger parts, but for the watch hands for example, which are much smaller and angled at various degrees, it wouldn't be quite as simple would it? – Dean Elliott Apr 24 '17 at 11:35
  • @DeanElliott i add [post](http://stackoverflow.com/a/43587875/7887530) to this question. I think splitting is easier :) – Zhenya Telegin Apr 24 '17 at 12:17

1 Answers1

6

You can use the HTML tag to do so, Please check the <area> tag in html it might serve your purpose.

Check the below code may help you:

W3 Schools - Areamap

And you can also use <canvas> or <svg> with the help of Fabric.js you can get the thing done in much more advance way.

Check this link you will get really cool stuff to do with image or canvas and svg:

MDN - Canvas API Tutorial

Thanks

function runfunc(planetId) {
  console.log('You selected:', planetId);
}
.as-console-wrapper { max-height: 2.8em !important; }
<p>Click on the Sun or on one of the planets to see which one was selected.</p>

<img src="https://www.w3schools.com/tags/planets.gif" width="145" height="126"
     alt="Planets" usemap="#planetmap">

<map name="planetmap">
  <area shape="rect" coords="0,0,82,126" alt="Sun" id="Sun" onclick="runfunc(this.id)">
  <area shape="circle" coords="90,58,3" alt="Mercury" id="Mercury" onclick="runfunc(this.id)">
  <area shape="circle" coords="124,58,8" alt="Venus" id="Venus" onclick="runfunc(this.id)">
</map>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
ankit verma
  • 616
  • 5
  • 17