简体   繁体   中英

Javascript check if transparent image on canvas has been clicked

I have a canvas, and I drew an image that is transparent, and has a polygon like shape. Now I need to check if that image has been clicked.

I have the cords { x:30, y:20, w:100, h:100 }

I could check for a box or circle Click but what if it is rigid like a polygon is there a pixel click test or the convex algorithm(But I don't want to have to specify the edges)?

Thank You.

One solution would be to implement pixel detection with a secondary canvas to be used as a map.

  1. Draw your shape onto your scene canvas.
  2. Draw the exact shape onto a second canvas, but set the color to rgb(0,0,0).
  3. Store that color as a reference in some sort of map to reference your first 'shape'

eg

var pixelMap = {
  '000' : 'rectangle 1',
  '001' : 'rectangle 2'
};

Every time you draw a new shape to the canvas, increase the rgb by 1. Unless you have over 16.7 million shapes (256^3), this method should suffice.

Heres an example implementation : https://jsfiddle.net/mikeschultz/nbtnxpf2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM