如何使用d3.js版本4用鼠标滚轮平移。

我发现使用v3的该示例,但不适用于v4。

Example link



<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<!DOCTYPE html>
<meta charset="utf-8">
<title>D3.js: Panning with mouse wheel</title>
<style>

.overlay {
  fill: none;
  pointer-events: all;
}

</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>

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 zoomer = d3.behavior.zoom()
  .on("zoom", zoom)

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
  .append("g")
    .call(zoomer)
      .on("wheel.zoom",pan)
  .append("g");

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

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

function zoom() {
    console.log(d3.select(this))
  svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}

function pan() {
    current_translate = d3.transform(svg.attr("transform")).translate;
    dx = d3.event.wheelDeltaX + current_translate[0];
    dy = d3.event.wheelDeltaY + current_translate[1];

  svg.attr("transform", "translate(" + [dx,dy] + ")");
  d3.event.stopPropagation();
}

</script>

最佳答案

我有同样的需求,并且弄清楚了D3v4(如下)中所需的更改。我还发布到了区块here



var width = 960,
    height = 500;

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

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

var zoomer = d3.zoom().scaleExtent([1 / 2, 4]).on("zoom", zoom)

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

var g = svg.append("g");

svg.call(zoomer)
   .on("wheel.zoom", null)
   .on("wheel", pan);

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

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

function zoom() {
  g.attr("transform", d3.event.transform);
}

function pan() {
  zoomer.translateBy(svg.transition().duration(100), d3.event.wheelDeltaX, d3.event.wheelDeltaY);
}

.overlay {
  fill: none;
  pointer-events: all;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.12.2/d3.min.js"></script>
<title>D3.js v4: Panning with mouse wheel</title>
<body></body>

关于javascript - 带鼠标滚轮的D3 v4锅,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46568677/

10-12 20:36