Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save billspat/3c58fd2c418c3791dca1aad602994b00 to your computer and use it in GitHub Desktop.
Save billspat/3c58fd2c418c3791dca1aad602994b00 to your computer and use it in GitHub Desktop.
D3 custom zoom to mouse position
// viewport dimensions
const WIDTH = 300;
const HEIGHT = 400;
// initial values
var tx = 0,
ty = 0,
scale = 1;
/**
* On mouse wheel callback
*/
function onWheel() {
// prevent default event behaviour
d3.event.preventDefault();
// set zooming
var factor = 1.1;
var center = d3.mouse(document.querySelector('svg'));
var newTx, newTy, newScale;
// calculate new scale
if (d3.event.deltaY > 0) {
newScale = scale * factor;
} else {
newScale = scale / factor;
}
// calculate new translate position
// [current mouse position] - ([current mouse position] - [current translate]) * magnification
newTx = center[0] - (center[0] - tx) * newScale / scale;
newTy = center[1] - (center[1] - ty) * newScale / scale;
// set new scale and translate position
scale = newScale;
tx = newTx;
ty = newTy;
svg.attr('transform', `translate(${tx}, ${ty}) scale(${scale})`);
}
// create svg
var svg = d3.select('body').append('svg')
.attr('width', WIDTH)
.attr('height', HEIGHT)
.on('wheel.zoom', onWheel)
.append('g')
.attr('transform', `translate(${tx}, ${ty}) scale(${scale})`);
// add rectangle
svg.append('rect')
.attr('width', WIDTH)
.attr('height', HEIGHT)
.attr('fill', '#fff')
.attr('x', 0)
.attr('y', 0);
// add circle
svg.append('circle')
.attr('cx', WIDTH / 2)
.attr('cy', HEIGHT / 2)
.attr('r', 40)
.attr('fill', '#996600');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment