How to detect one element sitting on top of another

I have this situation:

enter image description here

I need to detect a situation where an element sits on top of another. These are the elements of SVG:

<circle r="210.56" fill="#1ABCDB" id="01" priority="4" cx="658" cy="386"></circle> <circle r="210.56" fill="#1ADC4A" id="02" priority="4" cx="858" cy="386"></circle> 

I have to figure out how to do this, maybe someone can give me some hint. I am using jQuery. Thanks a lot for the help.

+4
source share
3 answers

Well, at least if you are dealing with circles, this is a little simple, because circles have a nice property: in order for the circles to overlap in any way, the sum of their radii must be greater than the distance between their two centers.

So it should be simple:

  • calculating the distance between two center points (it’s easy enough to get the centers as they are defined in the <circle> element, and
  • add two radius values ​​(again, in the <circle> element), then
  • just compare. If the sum of the radius is greater than the distance, then you have an overlap .

http://jsfiddle.net/sZ9N9/

+1
source

You can see this function:

http://jsfiddle.net/a9bnh/

 function upperElements(el) { var top = el.offsetTop, left = el.offsetLeft, width = el.offsetWidth, height = el.offsetHeight, elemTL = document.elementFromPoint(left, top), elemTR = document.elementFromPoint(left + width - 1, top), elemBL = document.elementFromPoint(left, top + height - 1), elemBR = document.elementFromPoint(left + width - 1, top + height - 1), elemCENTER = document.elementFromPoint(parseInt(left + (width / 2)), parseInt(top + (height / 2))), elemsUpper = []; if (elemTL != el) elemsUpper.push(elemTL); if (elemTR != el && $.inArray(elemTR, elemsUpper) === -1) elemsUpper.push(elemTR); if (elemBL != el && $.inArray(elemBL, elemsUpper) === -1) elemsUpper.push(elemBL); if (elemBR != el && $.inArray(elemBR, elemsUpper) === -1) elemsUpper.push(elemBR); if (elemCENTER != el && $.inArray(elemCENTER, elemsUpper) === -1) elemsUpper.push(elemCENTER); return elemsUpper; }; 
0
source

Richard's answer is good if there are 2 circles, but if there are a lot of them, I would suggest the following steps

  • Calculation of the area covered by overlapping circles
  • Calculating the sum of the areas of all circles independently (since these are SVGs and circle radii are known, this would be easy to do)
  • Comparison of two areas
  • If the two areas are the same, then there is no overlap, otherwise at least 2 circles overlap.

The difficult step is step 1, which can be calculated using the pixel painting algorithm (my preference). For other methods, you can go to the next question about the surface_ stack

0
source

Source: https://habr.com/ru/post/1486229/


All Articles