如何在 ViewBox 中使用 D3 缩放行为而不是变换

Dou*_*ghy 5 svg viewbox zooming d3.js

我想利用 D3 的缩放行为功能,但我需要使用 viewBox 属性而不是 D3 示例中所示的转换方法对我的 SVG 进行所有转换/缩放:http : //bl.ocks.org/ mbostock/3680999

如何仅使用 viewBox 实现相同的缩放/平移?到目前为止,这是我的代码,它不像转换方法那样工作得很好。

function zoomed(d) {
  if (!scope.drawLine) {
    var scale = d3.event.scale;
    var translation = d3.event.translate;

    //This works, but I can't use it for reason's I won't go into now
    //mapSVG_G.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");

    var newViewBox = [
      initialViewBox[0] - translation[0],
      initialViewBox[1] - translation[1],
      initialViewBox[2]/scale,
      initialViewBox[3]/scale
      ];
      mapSVG.attr('viewBox', newViewBox);
    }
}
Run Code Online (Sandbox Code Playgroud)

eag*_*gor 2

有点偏离,但可以作为你的开始:

主要作品:

var newViewBox = [
    -translate[0] / scale,
    -translate[1] / scale,
    width / scale,
    height / scale
].join(" ");
Run Code Online (Sandbox Code Playgroud)

整个例子:

var newViewBox = [
    -translate[0] / scale,
    -translate[1] / scale,
    width / scale,
    height / scale
].join(" ");
Run Code Online (Sandbox Code Playgroud)
var width = 960,
  height = 500;

var randomX = d3.random.normal(width / 2, 80),
  randomY = d3.random.normal(height / 2, 80);

var data = d3.range(2000).map(function() {
  return [
    randomX(),
    randomY()
  ];
});

var svg = d3.select("body").append("svg")
  .attr("width", width)
  .attr("height", height)
  .attr("viewBox", [0, 0, width, height].join(" "))

var vis = svg.append("g")
  .call(d3.behavior.zoom().scaleExtent([1, 8]).on("zoom", zoom))
  .append("g");

vis.append("rect")
  .attr("class", "overlay")
  .attr("width", width)
  .attr("height", height);

vis.selectAll("circle")
  .data(data)
  .enter().append("circle")
  .attr("r", 2.5)
  .attr("transform", function(d) {
    return "translate(" + d + ")";
  });

function zoom() {
  var scale = d3.event.scale;
  var translate = d3.event.translate;

  var newViewBox = [
    -translate[0] / scale,
    -translate[1] / scale,
    width / scale,
    height / scale
  ].join(" ");
  
  svg.attr('viewBox', newViewBox);

}
Run Code Online (Sandbox Code Playgroud)
.overlay {
  fill: none;
  pointer-events: all;
}
Run Code Online (Sandbox Code Playgroud)