Click on given element in canvas

2019-02-24 06:19发布

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).

3条回答
We Are One
2楼-- · 2019-02-24 06:29

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/

查看更多
Root(大扎)
3楼-- · 2019-02-24 06:41

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.

查看更多
地球回转人心会变
4楼-- · 2019-02-24 06:44

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

查看更多
登录 后发表回答