Created
June 14, 2016 21:24
-
-
Save KarolAltamirano/b54c263184be0516a59d6baf7f053f3e to your computer and use it in GitHub Desktop.
D3 custom zoom to mouse position
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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