d3缩放和平移升级到版本4

时间:2016-07-19 13:17:16

标签: d3.js

帮助我们会感谢更新以下代码以便在版本4中运行。我已将zoom.behaviour更改为d3.zoom但我不清楚所需的其他更改。它看起来比v3更复杂!

<!DOCTYPE html>
<html>
  <head>
   <!-- <script type="text/javascript" src="http://d3js.org/d3.v3.js"></script>-->

   <script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>

    <style type="text/css">
      body, html {
        width: 100%;
        height: 100%;
        margin: 0;
      }
      svg {
        position: absolute;
        top: 0;
        left: 0;
      }
      p {
        text-align: center;
      }
    </style>
  </head>
  <body>
    <p>Use the mouse to pan (click and move) / zoom (scrollwheel)</p>
  </body>
  <script type="text/javascript">
      var svg = d3.select("body")
        .append("svg")
        .attr("width", "100%")
        .attr("height", "100%")
        .call(d3.zoom().on("zoom", function () {
            svg.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")")
        }))
        .append("g")

      svg.append("circle")
        .attr("cx", document.body.clientWidth / 2)
        .attr("cy", document.body.clientHeight / 2)
        .attr("r", 50)
        .style("fill", "#B8DEE6")
  </script>
</html>

3 个答案:

答案 0 :(得分:34)

改变这个:

.call(d3.zoom().on("zoom", function () {
    svg.attr("transform", "translate(" + d3.event.translate 
    + ")" + " scale(" + d3.event.scale + ")")
}))

对此:

.call(d3.zoom().on("zoom", function () {
        svg.attr("transform", d3.event.transform)
}))

这是小提琴:https://jsfiddle.net/gerardofurtado/c8bga82b/

答案 1 :(得分:9)

我无法回答您对该答案的评论,但以下是如何仅缩放x轴:

svg.attr(
    "transform",
    'translate('+d3.event.transform.x+',0) scale('+d3.event.transform.k+',1)'
)}))

更新了jsFiddle:https://jsfiddle.net/axge6a04/1/

答案 2 :(得分:3)

接受的答案很棒!

对于那些想要限制 pan&amp; amp;放大边界(如here)..

改变这个:

// width, height = viewport width, height
.call(d3.zoom().on("zoom", function () {
  var tx = Math.min(0, Math.max(d3.event.translate[0], width - width * d3.event.scale));
  var ty = Math.min(0, Math.max(d3.event.translate[1], height - height * d3.event.scale));
  svg.attr("transform", "translate(" + [tx, ty] + ") scale(" + d3.event.scale + ")");
});

对此:

.call(d3.zoom().on("zoom", function () {
  d3.event.transform.x = Math.min(0, Math.max(d3.event.transform.x, width - width * d3.event.transform.k));
  d3.event.transform.y = Math.min(0, Math.max(d3.event.transform.y, height - height * d3.event.transform.k));
  svg.attr("transform", d3.event.transform);
}));