2

I have the following Particle script (as found and edit from teh webs!): http://jsfiddle.net/neuroflux/hSkFX/1/

I was wondering what the easiest way to make each particle "clickable" is?

I understand that these are not elements, rather x/y/radius points.

What would be the easiest way do you think?

Cheers!

[edit] This question is about click areas not click events....

Barrie Reader
  • 10,647
  • 11
  • 71
  • 139
  • 1
    possible duplicate of [Click on given element in canvas](http://stackoverflow.com/questions/3213877/click-on-given-element-in-canvas); also see [Click area on sprite in canvas](http://stackoverflow.com/questions/5948251/click-area-on-sprite-in-canvas) – mellamokb Aug 23 '12 at 12:31
  • I think you'd have to catch clicks on the `` and then see if the clicked coordinate is the location of one or more particles. – Pointy Aug 23 '12 at 12:32
  • no no no, it's not about click events... it's about getting the click area of the particle... – Barrie Reader Aug 23 '12 at 12:35
  • only if they are not elementary, I suppose (http://en.wikipedia.org/wiki/Elementary_particle) – KooiInc Aug 23 '12 at 12:50
  • How is click area and clicks not related? It is the same thing. A particle has an x diameter and it is centered at a certain position. When you create a particle or edit, store a reference to it in an array for click look up. – epascarello Aug 23 '12 at 13:56

2 Answers2

4

There is no way to really know that you clicked on an element in the canvas. What you do know is what x/y position the user click on the canvas object. You can take that x/y position and figure out if something is there. Another option is to check the pixel color there and see if it is colored.

epascarello
  • 204,599
  • 20
  • 195
  • 236
1

I found this tutorial particularly helpful! http://simonsarris.com/blog/510-making-html5-canvas-useful This is the relevant part you need:

// Determine if a point is inside the shape's bounds
    Shape.prototype.contains = function(mx, my) {
// All we have to do is make sure the Mouse X,Y fall in the area between
// the shape's X and (X + Height) and its Y and (Y + Height)
    return  (this.x <= mx) && (this.x + this.w >= mx) &&
          (this.y <= my) && (this.y + this.h >= my);
    }

You need to implement the .contains function to your Circle() objects, however you will have to change the the method by comparing the distance of the cursor's position from the centre of the circle with the circle radius and return one if smaller.

Vlad Otrocol
  • 2,952
  • 7
  • 33
  • 55