Rog*_*ana 3 javascript svg d3.js
我试图重现这篇文章中解释的SVG的行为,但将 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>
Run Code Online (Sandbox Code Playgroud)
但这不起作用。在 Firefox 中尝试时,错误是
类型错误:root.getIntersectionList 不是函数
在 Chrome 中,没有错误,但该函数似乎不起作用,因为列表中的结果始终为空。
有没有办法调用该函数,或者我应该使用其他方法检测该点是否在路径内部?
Firefox 错误是预料之中的,因为该浏览器尚不支持getInsectionList方法: https: //bugzilla.mozilla.org/show_bug.cgi ?id=501421
关于 Chrome,我认为您存在一个计时问题,即在执行调用时未呈现 svg 节点getIntersectionList。如果将代码推到事件循环的末尾,它应该可以工作:
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)
Run Code Online (Sandbox Code Playgroud)
无论如何,您可能会将其包含在其他事件(例如鼠标单击)中,但上面的内容应该可以让您证明这个概念。
关于相交测试的替代方法(除非您仅支持 Chrome,否则您可能需要这种方法),请参阅此问题:d3 - see what is at a certain x,y position
还有另一个与代码效率无关的建议:d3 有一个node() 方法,它为您提供选择的底层 DOM 节点。由于您已经拥有对 d3 的 svg 对象的引用,因此您可以更改此设置:
var root = document.getElementById("svgBox");
Run Code Online (Sandbox Code Playgroud)
对此:
var root = svg.node();
Run Code Online (Sandbox Code Playgroud)