mouseover circle HTML5 canvas

孤街浪徒 提交于 2019-12-09 00:42:47

问题


I am wondering how to set an area as a semi-complex shape (circle) defined in the canvas so when the user mouse overs the shape, a function will be called.

I do not wish to use libraries at all such as KineticJS etc.

Currently I have added an event listener to the canvas element so that on mouse move I call multiple functions; one of which works out the mouse x/y coordinates relative to the canvas. As such, any rectangular shape is easy to 'listen' for using a basic if statement (as the canvas is interactive and redrawn each mouse move).

For circular objects, as well as say triangular objects, is there a way to use a similar method using trigonometry and an if statement?

Or are there better ways to have multiple areas on a canvas which on mouse over, call a function?

Cheers


回答1:


If you know where the mouse is and you know where the circle is on the canvas then the mouse is inside the circle when the distance from the mouse to the center of the circle is less that the radius. If that's true manually call what ever you need to call.

Hope that helped




回答2:


If you are going to have multiple semi-complex shapes and don't want to have to make any complicated math functions, you can always use a ghost canvas.

The idea is that when you want to test for a shape, you draw each relevant shape to a canvas in-memory and test the mouse x/y pixel to see if something is there.

I detail how to do it in this tutorial.

It works beautifully for smaller amounts of objects, but if you plan on having more than ~200 objects on the screen, you will want to switch to faster, mathematical methods.



来源:https://stackoverflow.com/questions/6505765/mouseover-circle-html5-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!