menu

JavaScript/Typescript - 16 Topics

DEEP DIVE INTO

JavaScript/Typescript

Topic:Pinch to Zoom

menu

To implement a "pinch-to-zoom" event in JavaScript, you need to track the positions of two touch points and calculate the change in the distance between them as the user spreads their fingers (to zoom in) or pinches them together (to zoom out). This gesture is commonly used on touch-enabled devices like smartphones and tablets to zoom in or out on content, such as images or maps.

Here's a step-by-step explanation of how to create a pinch-to-zoom event in JavaScript:

1. Initialize Variables:

Initialize variables to keep track of the initial distance between the two touch points and whether a pinch gesture is in progress.

javascriptvar initialDistance; // Stores the initial distance between touch points
var currentDistance; // Initialize a variable to store the current distance between touch points
var isPinching = false; // Indicates whether a pinch gesture is in progress

2. Touch Start Event:

Listen for the touchstart event to detect when two fingers touch the screen.

javascriptelement.addEventListener("touchstart", function(event) {
  if (event.touches.length === 2) {
    // If two fingers touch the screen, start tracking the pinch
    let touch1 = event.touches[0];
    let touch2 = event.touches[1];
    initialDistance = calculateDistance(touch1, touch2);
    isPinching = true;
  }
});

In this event, you check if there are two touch points (fingers) on the screen. If so, you calculate and store the initial distance between them, indicating that a pinch gesture has begun.

3. Touch Move Event:

Listen for the touchmove event to track the movement of the two touch points.

javascriptelement.addEventListener("touchmove", function(event) {
  if (!isPinching) return; // Ignore touchmove events if a pinch hasn't started

  if (event.touches.length === 2) {
    // If two fingers are still on the screen, continue tracking the pinch
    let touch1 = event.touches[0];
    let touch2 = event.touches[1];
    currentDistance = calculateDistance(touch1, touch2);

    // Calculate the scaling factor based on the change in distance
    let scale = currentDistance / initialDistance;

    // Adjust the zoom level or content size based on the scale factor
    // For example, you can set the CSS `transform` property to scale the content.
    //Here contentElement is the id of dom element which you can get by document.getElementByID()
    let contentElement = document.getElementById('contentElement');
    contentElement.style.transform = `scale(${scale})`;
  }
});

In the touchmove event, you continue tracking the pinch by calculating the current distance between the two touch points and determining the scaling factor based on the change in distance. The scale variable represents the zoom factor, and you can use it to adjust the zoom level or size of the content accordingly.

4. Touch End Event:

Listen for the touchend event to reset the pinch gesture state.

javascriptelement.addEventListener("touchend", function(event) {
  isPinching = false; // Reset the pinch state when the touch ends
});

When the user lifts their fingers off the screen, you reset the isPinching flag to indicate that the pinch gesture has ended.

5. Helper Function:

Define a helper function, calculateDistance, to calculate the distance between two touch points.

javascriptfunction calculateDistance(touch1, touch2) {
  let deltaX = touch1.pageX - touch2.pageX;
  let  deltaY = touch1.pageY - touch2.pageY;
  return Math.sqrt(deltaX * deltaX + deltaY * deltaY);
}

This function calculates the Euclidean distance between two touch points, which is used to determine the distance between the fingers during the pinch gesture.

By following these steps and adjusting the zoom operation based on the scale factor, you can create a pinch-to-zoom event in JavaScript that allows users to zoom in or out on content in touch-enabled web or mobile applications.

Complete code

javascriptlet initialDistance; // Initialize a variable to store the initial distance between touch points
let  currentDistance; // Initialize a variable to store the current distance between touch points
let  isPinching = false; // Initialize a variable to track if a pinch is in progress

element.addEventListener("touchstart", function(event) {
  if (event.touches.length === 2) {
    // If two fingers touch the screen, start tracking the pinch
    let touch1 = event.touches[0];
    let touch2 = event.touches[1];
    initialDistance = calculateDistance(touch1, touch2);
    isPinching = true;
  }
});

element.addEventListener("touchmove", function(event) {
  if (!isPinching) return; // Ignore touchmove events if a pinch hasn't started

  if (event.touches.length === 2) {
    // If two fingers are still on the screen, continue tracking the pinch
    let touch1 = event.touches[0];
    let touch2 = event.touches[1];
    currentDistance = calculateDistance(touch1, touch2);

    // Calculate the scaling factor based on the change in distance
    let scale = currentDistance / initialDistance;

    // Adjust the zoom level or content size based on the scale factor
    // For example, you can set the CSS `transform` property to scale the content.
    //Here contentElement is the id of dom element which you can get by document.getElementByID()
    let contentElement = document.getElementById('contentElement');
    contentElement.style.transform = `scale(${scale})`;
  }
});

element.addEventListener("touchend", function(event) {
  isPinching = false; // Reset the pinch state when the touch ends
});

function calculateDistance(touch1, touch2) {
  let deltaX = touch1.pageX - touch2.pageX;
  let  deltaY = touch1.pageY - touch2.pageY;
  return Math.sqrt(deltaX * deltaX + deltaY * deltaY);
}
1280 x 720 px