获取给定坐标下的SVG-Object_s? [英] Get SVG-Object_s at given coordinates?

查看:71
本文介绍了获取给定坐标下的SVG-Object_s?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过坐标从SVG文件中获取对象ID.

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

例如

<?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)应该返回一个包含rectBLUE
  • 的列表
  • getObjectsAt(25,25)应该返回一个包含rectREDrectBLUE
  • 的列表
  • getObjectsAt(10,10)应该返回类似NIL
  • 的内容
  • 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?

推荐答案

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/

这篇关于获取给定坐标下的SVG-Object_s?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆