开发者

Locate an element within SVG in Opera by coordinates

开发者 https://www.devze.com 2022-12-19 22:27 出处:网络
How do I locate an element within SVG in Opera, 开发者_JS百科given coordinates? elementFromPoint(x,y) works fine with Firefox, but seems to fail with Opera, returning always the whole SVG and not the

How do I locate an element within SVG in Opera, 开发者_JS百科given coordinates?

elementFromPoint(x,y) works fine with Firefox, but seems to fail with Opera, returning always the whole SVG and not the particular element.

One might wonder why do I need it at all. Well, simply because I'd like to highlight the SVG element under the cursor, and because Opera doesn't fire any event when an element under the cursor is added/deleted, before you make a move with a mouse. That is, when I add a new element, it is not highlighted before I move the mouse slightly, which doesn't look nice.

Cheers, Mikhail.


In Opera there is SVG1.1's SVGSVGElement.getIntersectionList.

var element= document.elementFromPoint(pageX, pageY);
if (element.localName.toLowerCase()=='svg' && 'getIntersectionList' in element) {
    var svgxy= Element_getPageXY(svg); // by the usual offsetLeft/offsetParent etc. method
    var rect= svg.createSVGRect();
    rect.x= pageX-svgxy[0];
    rect.y= pageY-svgxy[1];
    rect.width=rect.height= 1;
    var hits= svg.getIntersectionList(rect, null);
    if (hits.length>0)
        element= hits[hits.length-1];
}

[Untested code, might even work.]


A way to do what you want without needing to look for the element under the cursor yourself is demonstrated in this example. Basically, you bind an event handler for the mouseover event to the root document element, then inspect the event's target to find out which element actually received the event.

For production code, you should add logic to take care of situations where the element is a <use> reference (by using target.correspondingUseElement to find out the id).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号