Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Move Image Focus via Device Orientation
<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8" />
<title>Panorama</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="image-wrapper">
<img class="image" src="http://lorempixel.com/1920/200" alt="Just a Placeholder Image">
</div>
</body>
</html>
window.onload = function() {
var img = null;
var img_W = null;
var initial_position = null;
var max_rotation = 75;
var screen_portrait = false;
if (window.innerWidth < window.innerHeight) screen_portrait = true;
var init_image = function() {
if (!img) {
img = document.querySelector('.image');
var imageHolder = document.querySelector('.image-holder');
img_W = img.offsetWidth - imageHolder.offsetWidth;
};
};
var position_image = function(percent) {
var pos = (img_W / 100)*percent;
img.style.transform = 'translate(-'+pos+'px)';
};
init_image();
position_image(50);
window.addEventListener('deviceorientation', function(e) {
if (initial_position === null) initial_position = e.alpha;
var current_position = initial_position - e.alpha;
var rotation = current_position;
if (screen_portrait) {
if (current_position > 180) rotation = current_position-360;
} else {
if (current_position < -180) rotation = 360+current_position;
}
if (rotation > max_rotation) rotation = max_rotation;
if (rotation < (0-max_rotation)) rotation = 0-max_rotation;
var percent = ((rotation + max_rotation)/(max_rotation*2))*100;
position_image(percent);
});
};
body {
margin: 0;
padding: 0;
}
img {
max-height: 100%;
}
.image-holder {
height: 110vh;
width: 100vw;
overflow: hidden;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.