728x90

Touch Events API는 모바일 장치에서 터치 기반 상호 작용을 처리하기 위한 일련의 이벤트, 메서드 및 속성을 제공하는 HTML5 사양의 일부입니다. 이 API를 사용하면 탭, 스와이프, 핀치, 회전과 같은 터치 이벤트를 감지하고 해당 이벤트를 기반으로 다양한 작업을 수행할 수 있습니다.

다음은 JavaScript에서 Touch Events API를 사용하는 방법에 대한 몇 가지 예입니다.

1. 터치 이벤트 감지:

element.addEventListener('touchstart', function(e) {

// code to handle touch start event

});

이 코드는 요소에 touchstart 이벤트 리스너를 연결하고 이벤트가 발생할 때 함수를 실행합니다. 이벤트 객체(`e`)에는 터치의 위치, 식별자 및 대상 요소와 같은 터치에 대한 정보가 포함됩니다.

2. 스와이프 이벤트 감지:

var xDown = null;

var yDown = null;

element.addEventListener('touchstart', function(e) {

xDown = e.touches[0].clientX;

yDown = e.touches[0].clientY;

});

element.addEventListener('touchmove', function(e) {

if (!xDown || !yDown) {

return;

}

var xUp = e.touches[0].clientX;

var yUp = e.touches[0].clientY;

var xDiff = xDown - xUp;

var yDiff = yDown - yUp;

if (Math.abs(xDiff) > Math.abs(yDiff)) {

if (xDiff > 0) {

// code to handle left swipe

} else {

// code to handle right swipe

}

} else {

if (yDiff > 0) {

// code to handle up swipe

} else {

// code to handle down swipe

}

}

xDown = null;

yDown = null;

});

이 코드는 시작(`touchstart`) 및 종료(`touchend`)할 때 터치의 위치를 추적하여 스와이프 이벤트를 감지합니다. 시작 위치와 종료 위치의 차이를 계산하여 스와이프 방향을 결정합니다.

3. 핀치 이벤트 감지:

var initialDistance = null;

element.addEventListener('touchstart', function(e) {

if (e.touches.length == 2) {

initialDistance = getDistance(e.touches[0], e.touches[1]);

}

});

element.addEventListener('touchmove', function(e) {

if (e.touches.length == 2) {

var currentDistance = getDistance(e.touches[0], e.touches[1]);

var delta = currentDistance - initialDistance;

if (delta > 0) {

// code to handle pinch in

} else if (delta < 0) {

// code to handle pinch out

}

}

});

function getDistance(p1, p2) {

var dx = p1.clientX - p2.clientX;

var dy = p1.clientY - p2.clientY;

return Math.sqrt(dx * dx + dy * dy);

}

이 코드는 화면에서 두 손가락 사이의 거리를 측정하여 핀치 이벤트를 감지합니다. 초기 거리(`touchstart`)와 현재 거리(`touchmove`) 사이의 차이를 계산하여 사용자가 핀치 인 또는 핀치 아웃하는지 여부를 결정합니다.

728x90

'IT' 카테고리의 다른 글

자바스크립트 "Storage Access API"  (0) 2023.03.11
자바스크립트 "Streams API"  (0) 2023.03.11
자바스크립트 "Trusted Types API"  (0) 2023.03.11
자바스크립트 "UI Events API"  (0) 2023.03.11
자바스크립트 "URL API"  (0) 2023.03.10

+ Recent posts