Created
June 2, 2017 07:12
-
-
Save kkxlkkxllb/8cfd5d723c6c2ffabbba508940fa5bfc to your computer and use it in GitHub Desktop.
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
var zoomIntensity = 0.2; | |
var canvas = document.getElementById("canvas"); | |
var context = canvas.getContext("2d"); | |
var width = 600; | |
var height = 200; | |
var scale = 1; | |
var originx = 0; | |
var originy = 0; | |
var visibleWidth = width; | |
var visibleHeight = height; | |
function draw(){ | |
// Clear screen to white. | |
context.fillStyle = "white"; | |
context.fillRect(originx,originy,800/scale,600/scale); | |
// Draw the black square. | |
context.fillStyle = "black"; | |
context.fillRect(50,50,100,100); | |
} | |
// Draw loop at 60FPS. | |
setInterval(draw, 1000/60); | |
canvas.onmousewheel = function (event){ | |
event.preventDefault(); | |
// Get mouse offset. | |
var mousex = event.clientX - canvas.offsetLeft; | |
var mousey = event.clientY - canvas.offsetTop; | |
// Normalize wheel to +1 or -1. | |
var wheel = event.wheelDelta/120; | |
// Compute zoom factor. | |
var zoom = Math.exp(wheel*zoomIntensity); | |
// Translate so the visible origin is at the context's origin. | |
context.translate(originx, originy); | |
// Compute the new visible origin. Originally the mouse is at a | |
// distance mouse/scale from the corner, we want the point under | |
// the mouse to remain in the same place after the zoom, but this | |
// is at mouse/new_scale away from the corner. Therefore we need to | |
// shift the origin (coordinates of the corner) to account for this. | |
originx -= mousex/(scale*zoom) - mousex/scale; | |
originy -= mousey/(scale*zoom) - mousey/scale; | |
// Scale it (centered around the origin due to the trasnslate above). | |
context.scale(zoom, zoom); | |
// Offset the visible origin to it's proper position. | |
context.translate(-originx, -originy); | |
// Update scale and others. | |
scale *= zoom; | |
visibleWidth = width / scale; | |
visibleHeight = height / scale; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment