Created
May 19, 2021 19:17
-
-
Save vlrmprjct/c24b19c0bc3a7ce31ec0d2244abd102a to your computer and use it in GitHub Desktop.
scrollzoom
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
const pos = { x: 0, y: 0 }; | |
const zoom_target = { x: 0, y: 0 }; | |
const zoom_point = { x: 0, y: 0 }; | |
const factor = 0.1; | |
const max_scale = 3; | |
let scale = 1; | |
const scrolled = (e) => { | |
const size = { | |
w: e.currentTarget.firstElementChild.offsetWidth, | |
h: e.currentTarget.firstElementChild.offsetHeight, | |
}; | |
zoom_point.x = e.pageX - e.currentTarget.offsetLeft; | |
zoom_point.y = e.pageY - e.currentTarget.offsetTop; | |
// e.preventDefault(); | |
var delta = e.deltaY; | |
// var delta = e.delta || e.originalEvent.wheelDelta; | |
// if (delta === undefined) { | |
// delta = e.originalEvent.detail; | |
// } | |
// cap the delta to [-1,1] for cross browser consistency | |
var capture = Math.max(-1, Math.min(1, delta * (-1))); | |
// determine the point on where the slide is zoomed in | |
zoom_target.x = (zoom_point.x - pos.x) / scale; | |
zoom_target.y = (zoom_point.y - pos.y) / scale; | |
// apply zoom | |
scale += capture * factor * scale; | |
scale = Math.max(1, Math.min(max_scale, scale)); | |
// calculate x and y based on zoom | |
pos.x = -zoom_target.x * scale + zoom_point.x; | |
pos.y = -zoom_target.y * scale + zoom_point.y; | |
// console.log(foo); | |
// console.log(scale); | |
// console.log(pos.x); | |
// Make sure the slide stays in its container area when zooming out | |
if (pos.x > 0) pos.x = 0; | |
if (pos.x + size.w * scale < size.w) pos.x = -size.w * (scale - 1); | |
if (pos.y > 0) pos.y = 0; | |
if (pos.y + size.h * scale < size.h) pos.y = -size.h * (scale - 1); | |
// update(); | |
// console.log('transform', 'translate(' + (pos.x) + 'px,' + (pos.y) + 'px) scale(' + scale + ',' + scale + ')'); | |
e.currentTarget.firstElementChild.style.transform = 'translate(' + (pos.x) + 'px, ' + (pos.y) + 'px) scale(' + scale + ', ' + scale + ')'; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment