HTML5 画布命中测试
我在 HTML5 Canvas 上绘制了一些图像,我想检查它们是否通过鼠标单击被击中。看起来很简单,我有图像的边界,但是图像被转换(平移和缩放)。不幸的是,上下文没有获取当前变换矩阵的方法,而且也没有用于矩阵乘法的 API。 似乎唯一的解决方案是自己跟踪变换并实现矩阵乘法。 欢迎提出建议。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这也是 3D (OpenGL) 图形世界中的常见问题。
解决方案是创建一个辅助画布对象(不显示),并在其中重新绘制图像。绘制与主画布绘制完全相同,只是每个元素都使用唯一的颜色绘制。然后,您查找与鼠标选择相对应的像素,并读出其颜色,这将为您提供相应的元素(如果有)。
这是OpenGL世界中常用的方法。您可以通过谷歌搜索术语找到它的描述,例如 “opengl 对象拾取”。这是众多搜索结果之一。
更新: HTML5 画布规范现在包括 命中区域。我还不确定浏览器对这些的支持程度。
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.