Skip to content

Instantly share code, notes, and snippets.

@sbrl
Last active December 20, 2015 20:30
Show Gist options
  • Select an option

  • Save sbrl/369ee8eb861e420f3100 to your computer and use it in GitHub Desktop.

Select an option

Save sbrl/369ee8eb861e420f3100 to your computer and use it in GitHub Desktop.
An (almost perfect) zoom function that zooms into the mouse cursor pointer. Assumes that the canvas is full screen - adjusting for this shouldn't be too tough.
/*
* An (almost perfect) zoom function that zooms into the mouse cursor pointer.
* Assumes that the canvas is full screen - adjusting for this shouldn't be too
* tough.
*
* Attaches a zoom level update function to the mouse wheel event of
* the document. Calling this activates zooming via the mouse wheel.
*
* Assumes that it is part of a class of sorts.
*
* this.canvas - The canvas
* this.offset - The panning offset that we should update
* this.zoom - The zoom level that we should update.
* this.zoomDelta - The amount that we should zoom by each time.
******************************************************************************
* Changelog
******************************************************************************
* 20th December 2015:
* Added this changelog.
*/
function trackMouseWheel() {
// Track the *vertical* mouse wheel movement
this.canvas.addEventListener("wheel", (function(event) {
// Calculate how much to change the zoom level by
var scrollDelta = 0;
if(event.deltaY < 0)
scrollDelta = this.zoomDelta;
else if(event.deltaY > 0)
scrollDelta = -this.zoomDelta;
// Calculate the new offset
this.offset = new Vector(
event.clientX + ((this.offset.x / (this.zoom - scrollDelta)) - (event.clientX / (this.zoom - scrollDelta))) * this.zoom,
event.clientY + ((this.offset.y / (this.zoom - scrollDelta)) - (event.clientY / (this.zoom - scrollDelta))) * this.zoom
);
// Update the zoom level
this.zoom += scrollDelta;
}).bind(this));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment