Javascript에서 가속도계 / 자이로 스코프 데이터에 액세스하는 방법은 무엇입니까?
최근에 랩톱의 가속도계 또는 자이로 스코프에 액세스하여 방향 또는 움직임의 변화를 감지하는 웹 사이트를 발견했습니다.
이것은 어떻게 이루어 집니까? window
객체 에서 어떤 종류의 이벤트를 구독해야 합니까?
어떤 기기 (노트북, 휴대 전화, 태블릿)에서 작동하는 것으로 알려져 있습니까?
주의 : 나는 실제로이 질문에 대한 답을 이미 알고 있으며, 바로 게시 할 것입니다. 여기에 질문을 게시하는 이유는 가속도계 데이터 가 Javascript (일부 장치)로 제공되고 커뮤니티가 해당 주제에 대한 새로운 결과를 게시하도록 요청하는 것입니다. 현재 이러한 기능에 대한 문서는 거의없는 것 같습니다.
현재 클라이언트 장치가 움직일 때 트리거되거나 트리거되지 않을 수있는 세 가지 별개의 이벤트가 있습니다. 그 중 두 주위에 초점을 맞추고있다 오리엔테이션 과의 마지막 동작 :
ondeviceorientation
데스크톱 버전의 Chrome에서 작동하는 것으로 알려져 있으며 대부분의 Apple 노트북에는 작동하는 데 필요한 하드웨어가있는 것으로 보입니다. iOS 4.2가 설치된 iPhone 4의 Mobile Safari에서도 작동합니다. 이벤트 핸들러 함수에서 액세스 할 수있는alpha
,beta
,gamma
함수의 유일한 인수로 제공 이벤트 데이터에 대한 값.onmozorientation
Firefox 3.6 이상에서 지원됩니다. 다시 말하지만 이것은 대부분의 Apple 랩톱에서 작동하는 것으로 알려져 있지만 가속도계가있는 Windows 또는 Linux 시스템에서도 작동 할 수 있습니다. 이벤트 핸들러 함수에서 첫 번째 인수로 제공된 이벤트 데이터x
에서y
,,z
필드를 찾으십시오 .ondevicemotion
iPhone 3GS + 4 및 iPad (iOS 4.2 모두)에서 작동하는 것으로 알려져 있으며 클라이언트 장치의 현재 가속과 관련된 데이터를 제공합니다. 핸들러 함수 가지고 전달 된 이벤트 데이터acceleration
및accelerationIncludingGravity
양쪽 축마다 세 개의 필드를 가지고 :x
,y
,z
"지진 감지"샘플 웹 사이트는 일련의 if
진술을 사용하여 어느 이벤트에 어떤 이벤트를 첨부 할 것인지 (약간의 우선 순위에 따라) 파악하고 수신 된 데이터를 공통 tilt
기능에 전달합니다 .
if (window.DeviceOrientationEvent) {
window.addEventListener("deviceorientation", function () {
tilt([event.beta, event.gamma]);
}, true);
} else if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion', function () {
tilt([event.acceleration.x * 2, event.acceleration.y * 2]);
}, true);
} else {
window.addEventListener("MozOrientation", function () {
tilt([orientation.x * 50, orientation.y * 50]);
}, true);
}
상수 요인 2와 50은 두 후자의 사건에서 읽은 값을 첫 번째 사건과 일치하는 데 사용되지만 결코 정확한 표현 은 아닙니다 . 이 간단한 "장난감"프로젝트의 경우 제대로 작동하지만 약간 더 심각한 데이터를 사용해야하는 경우 다른 이벤트에서 제공되는 값의 단위에 익숙해 져야하고 존중해야합니다.
다른 게시물의 훌륭한 설명에 의견을 추가 할 수는 없지만 훌륭한 문서 소스를 여기 에서 찾을 수 있다고 언급하고 싶었 습니다 .
가속도계에 대한 이벤트 기능을 다음과 같이 등록하면 충분합니다.
if(window.DeviceMotionEvent){
window.addEventListener("devicemotion", motion, false);
}else{
console.log("DeviceMotionEvent is not supported");
}
핸들러와 함께 :
function motion(event){
console.log("Accelerometer: "
+ event.accelerationIncludingGravity.x + ", "
+ event.accelerationIncludingGravity.y + ", "
+ event.accelerationIncludingGravity.z
);
}
그리고 자력계의 경우 다음과 같은 이벤트 핸들러를 등록해야합니다.
if(window.DeviceOrientationEvent){
window.addEventListener("deviceorientation", orientation, false);
}else{
console.log("DeviceOrientationEvent is not supported");
}
핸들러와 함께 :
function orientation(event){
console.log("Magnetometer: "
+ event.alpha + ", "
+ event.beta + ", "
+ event.gamma
);
}
There are also fields specified in the motion event for a gyroscope but that does not seem to be universally supported (e.g. it didn't work on a Samsung Galaxy Note).
There is a simple working code on GitHub
The way to do this in 2019+ is to use DeviceOrientation
API. This works in most modern browsers on desktop and mobile.
window.addEventListener("deviceorientation", handleOrientation, true);
After registering your event listener (in this case, a JavaScript function called handleOrientation()), your listener function periodically gets called with updated orientation data.
The orientation event contains four values:
DeviceOrientationEvent.absolute
DeviceOrientationEvent.alpha
DeviceOrientationEvent.beta
DeviceOrientationEvent.gamma
The event handler function can look something like this:
function handleOrientation(event) { var absolute = event.absolute; var alpha = event.alpha; var beta = event.beta; var gamma = event.gamma; // Do stuff with the new orientation data }
Usefull fallback here: https://developer.mozilla.org/en-US/docs/Web/Events/MozOrientation
function orientationhandler(evt){
// For FF3.6+
if (!evt.gamma && !evt.beta) {
evt.gamma = -(evt.x * (180 / Math.PI));
evt.beta = -(evt.y * (180 / Math.PI));
}
// use evt.gamma, evt.beta, and evt.alpha
// according to dev.w3.org/geo/api/spec-source-orientation
}
window.addEventListener('deviceorientation', orientationhandler, false);
window.addEventListener('MozOrientation', orientationhandler, false);
'IT' 카테고리의 다른 글
Java에서 String 클래스가 final로 선언 된 이유는 무엇입니까? (0) | 2020.06.28 |
---|---|
PHP에서 두 문자열의 차이점을 강조 (0) | 2020.06.28 |
파이썬에서 두 목록에 동일한 요소가 포함되어 있다고 주장하는 방법은 무엇입니까? (0) | 2020.06.28 |
ThreadStatic 속성은 어떻게 작동합니까? (0) | 2020.06.28 |
git clone --mirror를 업데이트하는 방법? (0) | 2020.06.28 |