我正在嘗試使用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(); });