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

时间:2015-07-10 23:02:02

标签: javascript d3.js

我正在研究这个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's document on d3.mouse,但没有用。谢谢。



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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:4)

因为,正如文件所述,

  

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

circle_01是D3选择,而不是DOM元素。在其上调用.node()获取底层DOM元素。