D3鼠标事件:使用selection.node()

d3 mouse event: using selection.node()

本文关键字:node selection 使用 鼠标 事件 D3      更新时间:2023-09-26

我正在研究这个D3示例http://bl.ocks.org/JohnDelacour/5673836(本页上的代码更容易阅读)

在这个函数中:

function follow_mouse() {
    var xy = d3.mouse(circle_01.node());
    var angle = (180/Math.PI * Math.atan2(xy[1], xy[0]));
    spoke_01.attr("transform", "rotate(" + angle + ")");
    report.text("Angle: " + angle.toFixed(2) + "°");
}

在第2行,为什么我们需要.node() ?

我在D3上读了D3的文档。老鼠,但它没有帮助。谢谢你。

var w = 960,  h = 500 , r = 150;
// selection.on(type[, listener[, capture]])
// type: "mousemove"
// listener: follow_mouse
var svg = d3.select("html").append("svg")
	.attr({width: w, height: h}) // assign multiple attributes
	.on("mousemove", follow_mouse); // call function when mouse moves
// angle reading
var report = svg.append("text") .attr("id", "report")
	.attr({x: 80, y: 80})
	.text("Angle: 0.00°");
// g0 at center
var g0 = svg.append("g").attr("id", "g0")
	.attr("transform", "translate(" + [w/2, h/2] + ")");
// draw arrow (path)
var spoke_01 = g0.append("path") .attr("id", "spoke_01")
	.attr("d", "M 0 0 h " + (r-2) + "l -9 3  2 -3 -2 -3 9 3");
// draw circle (circle)
var circle_01 = g0.append("circle").attr("id", "circle_01")
	.attr("r", r);
// https://github.com/mbostock/d3/wiki/Selections#d3_mouse
// this is an event listener. return value is ignored.
function follow_mouse() {
	var xy = d3.mouse(circle_01.node());
	var angle = (180/Math.PI * Math.atan2(xy[1], xy[0]));
	spoke_01.attr("transform", "rotate(" + angle + ")");
	report.text("Angle: " + angle.toFixed(2) + "°");
}
svg {
	background-color: #ddf;
}
#circle_01 {
	fill: white;
	fill-opacity: 0;
	stroke: darkorchid;
	stroke-width: 2;
}
#spoke_01 {
	fill: none;
	stroke: #602;
	stroke-width: 2;
	stroke-linecap: round;
}
#report {
	fill: #602;
	stroke: none;
	font: 16pt sans-serif;
}
<!DOCTYPE html>
<html lang="en">
<head>
	<link type="text/css" href="test.css" rel="stylesheet">
	<script src="http://d3js.org/d3.v3.min.js"></script>
</head>
<body>
  <script src="test.js" charset="utf-8"></script>
</body>
</html>

因为,正如文档所述,

容器可以是HTML或SVG容器元素,例如SVG:g或SVG: SVG。

circle_01是D3选择,而不是DOM元素。在它上面调用.node()得到底层DOM元素