Asking Questions
Asking Questions

Reputation: 404

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.

Upvotes: 1

Views: 491

Answers (1)

mike-schultz
mike-schultz

Reputation: 2364

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'

e.g.

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/

Upvotes: 3

Related Questions