-
Notifications
You must be signed in to change notification settings - Fork 1
/
tiltingcard_gyro.js
43 lines (37 loc) · 1.43 KB
/
tiltingcard_gyro.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
window.onload = function() {
if (isMobileDevice()) {
requestDeviceOrientation();
}
};
function isMobileDevice() {
return 'ontouchstart' in window || navigator.maxTouchPoints;
}
function handleOrientation(e) {
console.log(e);
let alpha = e.alpha;
let beta = e.beta;
let gamma = e.gamma;
let cardX = Math.max(-30, Math.min(beta - 90, 30));
let cardY = Math.max(-30, Math.min(gamma, 30));
let card = document.getElementsByClassName('tiltingContent')[0]; // Get the first element
card.style.transform = 'rotateX(' + cardX + 'deg) rotateY(' + cardY + 'deg) rotateZ(0deg)'; //https://stackoverflow.com/questions/27303339/transform-not-working-on-ios
}
async function requestDeviceOrientation() {
if (typeof DeviceOrientationEvent !== 'undefined' && typeof DeviceOrientationEvent.requestPermission === 'function') {
// iOS 13+
try {
const permissionState = await DeviceOrientationEvent.requestPermission();
if (permissionState === 'granted') {
window.addEventListener('deviceorientation', handleOrientation);
}
} catch (error) {
console.error(error);
}
} else if ('DeviceOrientationEvent' in window) {
// Not iOS 13+
window.addEventListener('deviceorientation', handleOrientation);
} else {
// Device orientation not supported
alert('Gyroscope not supported');
}
}