我正在尝试重现 this SVG 的行为在 this post 解释,而是将 JavaScript 放在 HTML 页面中,并使用 D3.js。我试试这个:
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="http://d3js.org/d3.v3.js"></script>
<script>
var svg = d3.select("body").append("svg")
.attr("width", 300)
.attr("height", 300)
.attr("id","svgBox");
var svgRect = svg.append("rect")
.attr("width", 200)
.attr("height", 200)
.attr("x", 50)
.attr("y", 50)
.attr("id","rect1")
.style("fill", "#AAFFAA")
.style("stroke", "#222222");
var root = document.getElementById("svgBox");
var rpos = root.createSVGRect();
rpos.x = 150;
rpos.y = 150;
rpos.width = rpos.height = 1;
var list = root.getIntersectionList(rpos, null);
console.info(list);
</script>
但它不起作用。在 Firefox 中尝试时,错误是
TypeError: root.getIntersectionList is not a function
而在 Chrome 中,没有错误,但该功能似乎不起作用,因为列表中的结果始终为空。
有没有办法调用该函数,或者我应该使用其他方法检测该点是否在路径内?
最佳答案
Firefox 错误是意料之中的,因为该浏览器尚不支持 getInsectionList
方法:https://bugzilla.mozilla.org/show_bug.cgi?id=501421
关于 Chrome,我认为您遇到了一个计时问题,即在您执行 getIntersectionList
调用时未呈现 svg 节点。如果将代码推到事件循环的末尾,它应该可以工作:
window.setTimeout(function(){
// your original code as-is:
var root = document.getElementById("svgBox");
var rpos = root.createSVGRect();
rpos.x = 150;
rpos.y = 150;
rpos.width = rpos.height = 1;
var list = root.getIntersectionList(rpos, null);
console.info(list);
},0)
无论如何,您可能会在其他一些事件(例如鼠标单击)中使用它,但是上面的内容应该可以让您证明这个概念。
关于交集测试的替代方法(除非您仅支持 Chrome,否则您可能需要),请参阅以下问题:d3 - see what is at a particular x,y position
还有一个与代码效率无关的建议:d3 有一个 node() method它为您提供了选择的基础 DOM 节点。由于您已经引用了 d3 的 svg 对象,因此您可以更改它:
var root = document.getElementById("svgBox");
为此:
var root = svg.node();
关于javascript - 来自 d3.js html 的 getIntersectionList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18146574/