我正在尝试使用 html、javascript 和 canvas 制作一个移动应用程序,基本上向下滚动会增加图像的缩放,向上滚动会减少图像的缩放,但我只能减少缩放,因为向上滚动时不断增加尺寸,我希望它减小尺寸。
部分javascript代码:
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粉8180888802023-10-09 10:11:10
要获取 Delta Y
,请使用以下代码来解决它,该代码存储触摸位置。
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(); });