【问题标题】:Get SVG-Object_s at given coordinates?在给定坐标处获取 SVG-Object_s?
【发布时间】:2015-06-10 11:59:39
【问题描述】:

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

例如在

<?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

有没有办法做到这一点?

【问题讨论】:

  • 如果您想得到答案,您需要提供更多信息。您使用哪种编程语言?你在使用任何库吗?
  • 主要是这个单一的任务——所以语言并不重要——快速而肮脏的脚本就可以了。 PHP 会非常好,因为 SVG 是通过 PHP 生成的——但即使这样也不是最优的,我想能够解决 getObjectsAt-Task 的语言也会做得更好;)
  • 添加一点细节:我生成非周期性图案(即 Penroses)——由许多多边形平铺的大型 SVG。现在我想尝试在这些非周期性网格上构建一个元胞自动机(如 Conways GOL)。问题是获取邻居单元的颜色 - 我希望通过 getObjectAt(x,y) 之类的方法来选择。

标签: svg coordinates


【解决方案1】:

document.elementFromPoint 方法,但它只返回最顶层的元素。要获得一个点下的所有元素,您可以找到最上面的元素,将其隐藏并再次查看该点,直到没有更多元素:

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/

【讨论】:

  • 再次感谢您!非常有用。
猜你喜欢
  • 1970-01-01
  • 2017-10-25
  • 1970-01-01
  • 2011-10-20
  • 1970-01-01
  • 2012-09-26
  • 2021-10-23
  • 2017-10-06
  • 2013-10-09
相关资源
最近更新 更多