Click on given element in canvas

2019-02-24 05:44发布

问题:

Is there any trick to determine if user clicks on given element rendered in canvas? For example I'm displaying rhombus from .png file with transparent background and i want to know if user click inside or outside that figure (like mouse-element collision).

回答1:

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



回答2:

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.



回答3:

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/