tags:

views:

367

answers:

2

Hi,

The browsers which have implemented parts of the SVG spec (Firefox etc) do hit-testing for us for free - if I attach a mousedown listener on an SVG object, I get notified whenever the shape is clicked. This is amazing, especially for complex polygon shapes.

I'm wondering if there's a way I can utilize this feature for a bit more hit testing. I want to know if a given rectangle intersects any of my SVG shapes.

For example, I add 3 complex polygons to my element. Now I want to know if rectangle (40, 40, 100, 100) intersects any of them. Does anyone have an idea how I could possibly hook into the already great hit-testing support available, instead of adding all this code myself?

Thanks

+1  A: 

I don't know of any way of intersecting a whole rectangle. But you can intersect a point, so you could build a more complicated check out of that:

var el= document.elementFromPoint(x, y);

will give you the highest-stacked element at a particular page-relative co-ordinate. You'll get the <svg> element if no shapes inside the SVG are hit.

This is a non-standard Mozilla extension, but it works on WebKit as well. Unfortunately, though it exists in Opera, it won't look inside <svg>, so on that browser the element will always be the SVGSVGElement.

bobince
+1  A: 

The SVG 1.1 DOM has just the right method (unfortunately it's not yet implemented in mozilla/webkit):

var nodelist = svgroot.getIntersectionList(hitrect, null);

For a full working example see this blogpost.

Erik Dahlström
great! So between us we've got all the main browsers. Well except for *that one*, obviously...
bobince
Ok so we just have to wait for this to be implemented in webkit then, following that safari and chrome then need to release a new version built against these changes.