Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 canvas hittesting

I have some images drawn on a HTML5 Canvas and I want to check if they are hit on mouse click. Seems easy, I have the bounds of the images, however the images are transformed (translated and scaled). Unfortunately, the context does not have a method to get the current transform matrix, and also, there is no API for matrices multiplication. Seems the only solution is to keep track of the transforms myself and implement matrix multiplication. Suggestions are welcomed.

like image 902
Valentin Iliescu Avatar asked Jun 30 '10 04:06

Valentin Iliescu


1 Answers

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

The solution is to create an auxiliary canvas object (which is not displayed), and to redraw your image into it. The draw is exactly the same as with your main canvas draw, except that each element gets drawn with a unique color. You then look up the pixel corresponding to your mouse pick, and read off its color, which will give you the corresponding element (if any).

This is a commonly used method in the OpenGL world. You can find descriptions of it by Googling terms like "opengl object picking". Here is one of the many search results.

Update: The HTML5 canvas spec now includes hit regions. I'm not sure to what degree these are supported by browsers yet.

like image 199
brainjam Avatar answered Sep 17 '22 23:09

brainjam