javascript 如何检测是否单击了形状(HTML5 画布)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14831186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to detect if a shape was clicked (HTML5 canvas)?
提问by Sandeep Kumar
I am drawing different shapes like rectangle, triangle, hexagon etc. using the canvas and lineTo
method like in this blog. I just want a simple way to find if I clicked inside a shape. I can do it by filling the shape with some color and the checking if the point I clicked has this color but I don't want to use fill color method. Is there any other way to do it?
我正在使用此博客中的画布和lineTo
方法绘制不同的形状,如矩形、三角形、六边形等。我只想要一种简单的方法来查找我是否在形状内部单击。我可以通过用某种颜色填充形状并检查我单击的点是否具有这种颜色来实现,但我不想使用填充颜色方法。有没有其他方法可以做到?
Also found isPointInPathbut it did not work.
还发现isPointInPath但它不起作用。
采纳答案by kidwon
Check in here:
在这里签到:
Javascript check Mouse clicked inside the Circle or Polygon
meouwanswer works for sure I've test it and guarantee it works. It seems that there are some other solutions, too that have been upvoted, maybe you can try them, either
meouw答案肯定有效我已经测试过并保证它有效。似乎还有一些其他的解决方案也被点赞了,也许你可以尝试一下,要么
回答by tmaximini
You could either try some canvas frameworks like http://kineticjs.com/(check events section) which support already clickable elements out of the box or you'll need to write two functions, one which gives you your relative mouse click coordinates inside the canvas element (I used the one described here: https://stackoverflow.com/a/5932203/532102) and after write another function which checks if the returned mouse coordinates intersect with your shape on the canvas.
您可以尝试一些画布框架,如http://kineticjs.com/(检查事件部分),它们支持开箱即用的可点击元素,或者您需要编写两个函数,一个函数为您提供内部的相对鼠标点击坐标画布元素(我使用了这里描述的元素:https: //stackoverflow.com/a/5932203/532102),然后编写另一个函数来检查返回的鼠标坐标是否与画布上的形状相交。