Created
April 19, 2018 07:19
-
-
Save tvandervossen/859b9f854b61bf8695fdd4c8eb00299e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// On iPhone and iPod Touch we add a nice dynamic 3D parallax effect by | |
// updating the perspective origin depending on device tilt. | |
if (/iPhone|iPod/.test(navigator.platform) && 'ondevicemotion' in window) { | |
;(function() { | |
var value, | |
element = $('div.doors ul').get(0), | |
values = {x: [0,0,0], y: [0,0,0]}, // Keep the 3 most recent values. | |
index = 0, | |
choices = { // Lookup table to normalize based on device orientation. | |
x: {'0': ['x', -1], '90': ['y', 1], '180': ['x', 1], '-90': ['y', -1]}, | |
y: {'0': ['y', 1], '90': ['x', 1], '180': ['y', -1], '-90': ['x', -1]} | |
} | |
// The devicemotion event is triggered at regular intervals, so this code | |
// is optimized to be fast rather than elegant. | |
window.ondevicemotion = function(event) { | |
// Get the device tilt and normalize its value to match the current | |
// orientation of the device. | |
values.x[index] = event.accelerationIncludingGravity[choices.x[window.orientation][0]] * choices.x[window.orientation][1] | |
values.y[index] = event.accelerationIncludingGravity[choices.y[window.orientation][0]] * choices.y[window.orientation][1] | |
index++ | |
if (index == 3) | |
index = 0 | |
// Average the 3 most recent values and create the css value string. | |
value = (50 + ((values.x[0] + values.x[1] + values.x[2]) / 3 * 10)) + '%' + (50 + ((values.y[0] + values.y[1] + values.y[2]) / 3 * 10)) + '%' | |
// Update the perspective origin based on the device tilt around the x | |
// and y axis. | |
element.style.perspectiveOrigin = value | |
element.style.webkitPerspectiveOrigin = value | |
} | |
})() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment