简体   繁体   中英

How to detect one element sitting on top of another

I have this situation:

在此输入图像描述

I need to detect situation when element sitting on top of another. This is SVG elements:

<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 clue how to do this, maybe someone can give me some hint. I use jQuery. Much thx for help.

Well, at least if you're dealing with circles, it's a bit simple, because circles have a nice property: for circles to overlap in any way, the sum of their radii should be greater than the distance between their two centers .

So it should just be a matter of:

  1. figuring out the distance between the two center points (easy enough to get the centers, as they're defined in the <circle> element, and
  2. add the two radius values (again, on the <circle> element), then
  3. just compare. If the radius sum is greater than the distance, then you've got an overlap .

http://jsfiddle.net/sZ9N9/

You could look at 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;
};

Richard's answer is good if there are 2 circles but if there are many then I would suggest the following steps

  1. Calculating the area covered by the overlapping circles
  2. Calculating the sum of areas of all the circles independently(since this is SVG and the radii of the circles are known, this would be easy to do)
  3. Comparing the 2 areas
  4. If the 2 areas are the same, then there is no overlapping otherwise at least 2 circles overlap.

The tricky step is step 1 which can be approximiately calculated using pixel painting algorithm(my preference). For other methods, you can go through the following stackoverflow question

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