虽然我有一个 JS fiddle 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)。但是,如果您拖动/缩放屏幕,它会快速回到居中之前的原始 View 。。搜索似乎说您需要重置缩放对象,但我没有看到我在哪里。
最佳答案
当您在此处创建 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 的 click
处理程序而不是通过字符串引用 center
函数解决了这个问题:
d3.select("#UI")
.append("button")
.attr("type","button")
.on("click",center)
.html("Center");
关于javascript - 缩放转换后, "camera"会回到缩放前的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22420768/