How to pinch-to-zoom and 2 finger pan a Fabric.js canvas
If you want to support the pinch-to-zoom gesture, and two-finger panning while using a trackpad on a webpage, you only need to check for one special property on the wheel event.
That special property is the ctrlKey
. Thanks to the research done in Kenneth’s blog post about detecting trackpad gestures in javascript, we see that Microsoft was the first to send pinch-to-zoom events to the browser by setting the ctrlKey to true on a wheel event, then all other browsers followed suit. The wheel event exposes three movement properties: deltaX, deltaY, and deltaZ, and the Chromium team initially thought to use deltaZ for zoom, but decided to not diverge from another browser that got there first, so now we have this weird ctrlKey
plus deltaY
hack.
When detecting a pinch, the event’s deltaY
value will be set to a value relative to the magnitude of the pinch. When performing a small pinch, the value will be small, maybe less than 1, and for a larger pinch the value can be 10, 30, 50+. So the code you write can easily reflect the user’s behavior.1
2
3
4
5
6
7
window.addEventListener("wheel", function(e) {
e.preventDefault()
if (e.ctrlKey) {
console.log("pinch detected")
console.log("zoom by a factor of", e.deltaY)
}
},{passive: false})
Demo
See the Pen Pinch to zoom and 2 finger pan by Sandro Turriate (@sandro) on CodePen.
Fabric.js demo
Adding this behavior to Fabric.js follows the same logic, but with slightly different event handlers. The code can be found in the following codepen example.
See the Pen Fabric.js pinch zoom two finger pan by Sandro Turriate (@sandro) on CodePen.