选择图像区域并触发JS事件

时间:2017-04-24 11:10:10

标签: javascript jquery html canvas

是否可以使用HTML画布或Javascript单击图像的一部分,并根据您单击的部分触发Javascript事件?

所以,例如;

如果我有一个手表的图像并且用户点击了表带,则会触发一个带有与表带有关的内容的模态。同样,如果他们点击其中一只表针,则会触发不同的模态。

2 个答案:

答案 0 :(得分:4)

您可以使用HTML标记执行此操作,请检查html中的<area>标记,它可能会满足您的需要。

检查以下代码可能会对您有所帮助:

  

W3 Schools - Areamap

您还可以在Fabric.js的帮助下使用<canvas><svg>,您可以更加先进地完成任务。

检查此链接,您将获得与图像或画布和svg相关的非常酷的东西:

  

MDN - Canvas API Tutorial

谢谢

&#13;
&#13;
function runfunc(planetId) {
  console.log('You selected:', planetId);
}
&#13;
.as-console-wrapper { max-height: 2.8em !important; }
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用Photoshop或任何其他图形编辑器分割图像。

1。这是我们的输入图片:

Input image

2。我们想把它拆分为表带和屏幕(3列×3行):

enter image description here

3。分割图片后,我们可以使用<img>代码添加我们的代码:(link to splited images)

单击图像检查输出:)

const clickHandler = (id) => {
  console.log(id, "clicked!");
}
img {
  // remove spaces between images
  margin-bottom: -4px;
  margin-left: -4px;
  margin-top: -4px;
}
<img src="https://i.imgur.com/l44Jq14.png" border="0" />
<img src="https://i.imgur.com/TIWY87s.png" border="0" id="strap" onclick="clickHandler(this.id)" />
<img src="https://i.imgur.com/au0ilco.png" />
<br>
<img src="https://i.imgur.com/UCqXjDR.png" />
<img src="https://i.imgur.com/rOEkIDx.png" id="screen" onclick="clickHandler(this.id)" />
<img src="http://i.imgur.com/fwhQ1cU.png" />
<br>
<img src="https://i.imgur.com/K9xeGng.png" />
<img src="https://i.imgur.com/16nFrhw.png" id="strap" onclick="clickHandler(this.id)" />
<img src="https://i.imgur.com/xI3tDmB.png" />