如何使用d3.js版本4使用鼠标滚轮平移。
我使用v3找到了这个例子,但它不适用于v4。
<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>
答案 0 :(得分:1)
我有同样的需求,我想出了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);
}
&#13;
.overlay {
fill: none;
pointer-events: all;
}
&#13;
<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>
&#13;