Blog>
Snippets

Implementing Pinch to Zoom

Track multiple touch points to calculate the scaling factor for implementing pinch-to-zoom functionality.
let pinchStartDistance = null;
let initialScale = 1;
let currentScale = 1;

const myElement = document.getElementById('zoomable-element');

myElement.addEventListener('touchstart', function(e) {
  if (e.touches.length === 2) {
    pinchStartDistance = getDistanceBetweenTouches(e);
  }
});

myElement.addEventListener('touchmove', function(e) {
  if (e.touches.length === 2) {
    e.preventDefault();
    const currentDistance = getDistanceBetweenTouches(e);
    currentScale = initialScale * (currentDistance / pinchStartDistance);
    myElement.style.transform = `scale(${currentScale})`;
  }
});

myElement.addEventListener('touchend', function(e) {
  if (e.touches.length < 2) {
    initialScale = currentScale;
  }
});

function getDistanceBetweenTouches(e) {
  const touch1 = e.touches[0];
  const touch2 = e.touches[1];
  return Math.sqrt(
    Math.pow(touch1.pageX - touch2.pageX, 2) +
    Math.pow(touch1.pageY - touch2.pageY, 2)
  );
}
This code sets up a pinch to zoom feature on an element with the ID 'zoomable-element'. It listens for touch events and, if two fingers are detected, calculates the distance between them to determine the scaling factor and applies a CSS transform to scale the element. It starts tracking the scale from the initial pinch and updates the scale on each touch move. When the fingers are lifted, it sets the new scale as the initial scale for subsequent interactions.