变焦过渡后,"相机"在缩放之前快速回到原来的位置

时间:2014-03-15 07:11:45

标签: javascript d3.js

虽然我有一个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)。但是,如果您拖动/缩放屏幕,它会在居中之前快速回到原始视图。搜索似乎表示您需要重置缩放对象,但我不知道我在哪里。

1 个答案:

答案 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");