虽然我有一个JS小提琴link here,但它并不适用于小提琴。
<body>
<script src="d3.js" charset="utf-8"></script>
<div id="graph"></div>
<div id="UI">
</div>
</body>
<script>
function center() {
var theGraph = d3.select("#container");
theGraph.transition()
.duration(750)
.attr("transform", "translate(0, 0)scale(1)");
}
var svgWidth = 0;
var svgHeight = 0;
var startX = 0;
var startY = 0;
// code ran on load
var svg = d3.select("#graph").append("svg").attr("id", "myGraph");
// zoom handler
svg.call(d3.behavior.zoom().on("zoom", redraw));
// load data & assign to graph.
// "container" holds all the SVG paths/groups
svg.attr("width", 500).attr("height", 500).append("g").attr("id", "container");
var container = svg.select("#container");
container.append("circle").attr("cx", 25).attr("cy", 25).attr("r", 25).style("fill", "purple");
// make the button
d3.select("#UI").append("button").attr("type","button").attr("onclick","center()").html("Center");
container.append("circle").attr("cx",100).attr("cy",50).attr("r", 10).style("fill", "blue");
function redraw() {
d3.select("#container").attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")");
}
</script>
源代码必须保存为html,并且目录中需要d3.js。
单击“中心”缩小并将屏幕转换为(0,0)。但是,如果您拖动/缩放屏幕,它会在居中之前快速回到原始视图。搜索似乎表示您需要重置缩放对象,但我不知道我在哪里。
答案 0 :(得分:2)
在此处创建d3.behavior.zoom
时,您确实拥有缩放对象:svg.call(d3.behavior.zoom().on('zoom', redraw)
。
正如您已经发现的那样,您必须在转换回center
时重置它:
var zoom = d3.behavior.zoom()
.on("zoom", redraw);
function center() {
var theGraph = d3.select("#container");
zoom.translate([0, 0]); // Resetting translate
zoom.scale(1); // Resetting scale
theGraph.transition()
.duration(750)
.attr("transform", "translate(0, 0)scale(1)");
}
// ...
svg.call(zoom);
工作演示:http://jsfiddle.net/EM2c6/2/
旁注:之前在jsFiddle
中没有工作:
d3.select("#UI")
.append("button")
.attr("type","button")
.attr("onclick", "center()") // <- This is not defined on the global scope
.html("Center");
使用D3&#39; click
处理程序,而不是通过字符串引用center
函数修复了该问题:
d3.select("#UI")
.append("button")
.attr("type","button")
.on("click",center)
.html("Center");