search

Home  >  Q&A  >  body text

Capturing Y coordinates using touchmove: a step-by-step guide

I'm trying to make a mobile app using html, javascript and canvas, basically scrolling down increases the zoom of the image and scrolling up decreases it, but I can only decrease the zoom because it keeps increasing as I scroll up size, I want it to reduce size.

Part of the javascript code:

document.addEventListener('touchmove', (event)=>{

  if (event.pageY < 0) {
    zoomLevel /= 1.1; // zoom out by 10%
  } else if (event.pageY > 0) {
    zoomLevel *= 1.1; // zoom in by 10%
  }

  if (zoomLevel < 1) {
    zoomLevel = 1;
  } else if (zoomLevel > 5) {
    zoomLevel = 5;
  }
  drawImage();

})


function drawImage() {

  ctx.clearRect(0, 0, canvasWidth, canvasHeight);
  // draw zoom area
  const imgWidth = img.width * zoomLevel;
  const imgHeight = img.height * zoomLevel;
  const imgX = canvasWidth / 2 - imgWidth / 2;
  const imgY = canvasHeight / 2 - imgHeight / 2;
  ctx.drawImage(img, imgX, imgY, imgWidth, imgHeight);

}

P粉996763314P粉996763314412 days ago698

reply all(1)I'll reply

  • P粉818088880

    P粉8180888802023-10-09 10:11:10

    To get Delta Y, use the following code to solve it, which stores the touch position.

    let zoomLevel = 1;
    
    document.addEventListener('touchstart', (event) => {
      y = event.touches[0].clientY;
    });
    
    document.addEventListener('touchmove', (event) => {
      const deltaY = event.touches[0].clientY - y;
      y = event.touches[0].clientY;
    
      zoomLevel = Math.min(5, Math.max(1, zoomLevel + deltaY * 0.01));
      drawImage();
    });
    

    reply
    0
  • Cancelreply