Last active
December 20, 2015 20:30
-
-
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.
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
| /* | |
| * 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