Skip to content

Instantly share code, notes, and snippets.

@ahmohamed
Forked from mbostock/.block
Last active January 31, 2023 23:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ahmohamed/82ac20ccc949470e3206 to your computer and use it in GitHub Desktop.
Save ahmohamed/82ac20ccc949470e3206 to your computer and use it in GitHub Desktop.
D3.js: Panning with mouse wheel

This example demonstrate how to remap D3 events. MouseWheel event is used to pan the chart in x and y directions. This example was created as an answer to this SO question (Refer to it for detailed explanation).

<!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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment