Javascript 变焦转换后,“摄影机”将捕捉回变焦前的位置

Javascript 变焦转换后,“摄影机”将捕捉回变焦前的位置,javascript,d3.js,Javascript,D3.js,虽然我有一把JS小提琴,但它在小提琴中不起作用 <body> <script src="d3.js" charset="utf-8"></script> <div id="graph"></div> <div id="UI"> </div> </body> <script> function center() {

虽然我有一把JS小提琴,但它在小提琴中不起作用

    <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。但是,如果拖动/缩放屏幕,它会捕捉回居中之前的原始视图。搜索似乎表明您需要重置缩放对象,但我看不出在哪里有缩放对象。

在此处创建d3.behavior.zoom时,确实有缩放对象:svg.calld3.behavior.zoom.on'zoom',重画

正如您已经发现的,您必须在转换回中心时重置它:

工作演示:

旁注:它以前在JSFIDLE中不起作用,因为:

d3.select("#UI")
  .append("button")
  .attr("type","button")
  .attr("onclick", "center()") // <- This is not defined on the global scope
  .html("Center");

回答得很好。我没有意识到d3.behavior.zoom.onzoom,redraw创建了一个“缩放”对象;我只是认为它类似于.attr,因为它在本例中返回了基本对象“behavior”,尽管它显然不是一个对象。至于sidenote,这是一个错误,原因很简单,因为示例代码与原始代码不同,我从JSON文件创建了图形,在同一个HTML文件中有和。@Sky很高兴能提供帮助:
d3.select("#UI")
  .append("button")
  .attr("type","button")
  .attr("onclick", "center()") // <- This is not defined on the global scope
  .html("Center");
d3.select("#UI")
  .append("button")
  .attr("type","button")
  .on("click",center)
  .html("Center");