Get SVG-Object_s at given coordinates?

こ雲淡風輕ζ 提交于 2020-01-15 07:24:05

问题


I'd like to obtain object IDs from an SVG-file via coordinates.

For example in

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
   xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" version="1.1"
   height="50" width="50">
   <rect id="rectRED"
	x="15" y="5" height="30" width="30"
        style="fill:#ff0000;fill-opacity:0.5;stroke:#000000;stroke-width:1.5" />
   <rect id="rectBLUE"
	x="5" y="15" height="30" width="30"
        style="fill:#0000ff;fill-opacity:0.5;stroke:#000000;stroke-width:1.5" />
</svg>
  • getObjectsAt(10,25) should return a List containing rectBLUE
  • getObjectsAt(25,25) should return a List containing rectRED and rectBLUE
  • getObjectsAt(10,10) should return something like NIL

Is there a way to accomplish this?


回答1:


There's document.elementFromPoint method, but it only returns the topmost element. To get all the elements under a point you could find the topmost one, hide it and look at the point again until no more elements are there:

var elementsAt = function( x, y ){
    var elements = [], current = document.elementFromPoint( x, y );
    // at least one element was found and it's inside a ViewportElement
    // otherwise it would traverse up to the <html> root of jsfiddle webiste.
    while( current &&  current.nearestViewportElement ){
        elements.push( current );
        // hide the element and look again
        current.style.display = "none";
        current = document.elementFromPoint( x, y );
    }
    // restore the display
    elements.forEach( function( elm ){
       elm.style.display = ''; 
    });
    return elements;
}

http://jsfiddle.net/duo02d38/



来源:https://stackoverflow.com/questions/30755696/get-svg-object-s-at-given-coordinates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!