开发者

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 cur开发者_运维技巧rent 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜