Click on given element in canvas

北城以北 提交于 2019-12-01 19:40:26

There is no concept of individual elements in a canvas - it is simply just an area that you're drawing pixels onto. SVG on the other hand is made up of elements which you can then bind events to. However there are a few approaches you can take to add click events to canvas:

  1. Position an html element that overlays the area on the canvas you want to be clickable. A for a rectangular area or an image map for something more irregular.

  2. Use separate canvases for each element that you want to be clickable.

  3. CAKE - I haven't used this myself, but it's description is "SVG sans the XML". This may cover your needs. Demos here http://glimr.rubyforge.org/cake/canvas.html#EditableCurve

One idea is to draw the image to a temporary canvas, then use getImageDate() to receive data for the pixel you are interested in, and check if its alpha value is 0 ( = transparent).

The following is a sketch of a solution. It is assumed that...

  1. x and y are the coordinates of the mouse click event
  2. you are looping over gameObjects, the current object being stored in the variable gameObject
  3. the game object has been initialized with an image, x and y coordinates

The following code would then check whether the click was on a transparent area:

var tempCanvas = document.createElement('canvas');
if (tempCanvas.getContext) {
  tempContext = tempCanvas.getContext('2d');
}
tempContext.drawImage(gameObject.img, 0, 0);
var imgd = tempContext.getImageData(x - gameObject.x, y - gameObject.y, 1, 1);
var pix = imgd.data;
if (pix[3] == 0) {
  // user clicked on transparent part of the image!
}

Note: This is probably quite inefficient. I'm sure someone can come up with a better solution.

I have solve this problem using kintech.js, tutorials and examples can be found: http://www.html5canvastutorials.com/kineticjs/html5-canvas-drag-and-drop-tutorial/

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