Skip to content

Instantly share code, notes, and snippets.

@framp
Last active July 26, 2020 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save framp/d2b5b31e579d8e6d0d0555d7c2e6ee23 to your computer and use it in GitHub Desktop.
Save framp/d2b5b31e579d8e6d0d0555d7c2e6ee23 to your computer and use it in GitHub Desktop.
<html>
<head>
<title>Pinch and Zoom + Panning + Rotation</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<style>
html,body {
overscroll-behavior-x: none;
overscroll-behavior-y: none;
touch-action: none;
height: 100%;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
}
.notice {
position: fixed;
top: 20px;
width: 100%;
text-align: center;
}
#square {
background: red;
width: 50px;
height: 50px;
}
</style>
</head>
<body>
<div class="notice">pinch and zoom (chrome, safari, firefox) + panning (chrome, safari, firefox) + rotation (safari only)</div>
<div id="square"></div>
<script>
const square = document.getElementById('square')
let x = 0, y = 0, scale = 1, rotation = 0, gestureInitX, gestureInitY, gestureInitRotation, gestureInitScale
const render = () => {
window.requestAnimationFrame(() => {
square.style.transform = `translate3D(${x}px, ${y}px, 0px) rotate(${rotation}deg) scale(${scale})`
})
}
window.addEventListener('wheel', (e) => {
e.preventDefault()
e.stopPropagation()
const pinchZoomMode = e.deltaX === 0 && e.deltaY !== (e.deltaY | 0);
if (pinchZoomMode) {
scale -= e.deltaY * 0.01
} else {
x -= e.deltaX / 2
y -= e.deltaY / 2
}
render()
}, { passive: false })
window.addEventListener("gesturestart", function (e) {
e.preventDefault()
e.stopPropagation()
gestureInitX = e.pageX - x
gestureInitY = e.pageY - y
gestureInitRotation = rotation
gestureInitScale = scale
})
window.addEventListener("gesturechange", function (e) {
e.preventDefault()
e.stopPropagation()
rotation = gestureInitRotation + e.rotation
scale = gestureInitScale * e.scale
x = e.pageX - gestureInitX
y = e.pageY - gestureInitY
render()
})
window.addEventListener("gestureend", function (e) {
e.preventDefault()
e.stopPropagation()
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment