HTML5 canvas hittesting

I have some images drawn on HTML5 canvas and I want to check if they hit with a mouse click. It seems easy, I have image borders, however the images are converted (translated and scaled). Unfortunately, in the context there is no method for obtaining the current transformation matrix, and there is also no API for matrix multiplication. It seems the only solution is to track the transforms themselves and implement matrix multiplication. Suggestions are welcome.

+6
html5 canvas hittest
source share
1 answer

This is a common problem in the 3D graphics world (OpenGL).

The solution is to create an auxiliary canvas object (which does not appear) and to redraw the image into it. The draw is exactly the same as with your main canvas pattern, except that each element is drawn with a unique color. Then you look at the pixel corresponding to your mouse and read its color, which will give you the corresponding element (if any).

This is a widely used method in the OpenGL world. You can find descriptions of it using Googling terms, such as "collecting opengl objects . " Here is one of many search results .

Update: The HTML5 canvas specification now has remote areas . I'm not sure to what extent they are supported by browsers.

+17
source share

All Articles