Skip to content

Instantly share code, notes, and snippets.

@cybear
Created February 12, 2011 17:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cybear/823896 to your computer and use it in GitHub Desktop.
Save cybear/823896 to your computer and use it in GitHub Desktop.
Testing out devicemotion on iPad.
<!DOCTYPE html>
<html><head>
<title>iPad device motion test</title>
<style>body,input,button{font-size:20px;}.thing{width:100px;height:100px;background-color:#ccc;position:absolute;top:360px;left:360px;}</style>
<script>
var x,y,z,thing1,thing2;
var accTrackObj = function(options){
var acc={},
accHistory=[{},{}],
fake=function(){
return {
x:accHistory[0].x-accHistory[1].x,
y:accHistory[0].y-accHistory[1].y,
z:accHistory[0].z-accHistory[1].z
};
},
ondevicemotion=function(e){
acc=e.accelerationIncludingGravity;
accHistory[1]=accHistory[0];
accHistory[0]={x:acc.x,y:acc.y,z:acc.z};
options.ondevicemotion&&options.ondevicemotion(acc, accHistory);
options.fake&&options.fake(fake());
},
onorientationchange=function(){
var orientationDeg=window.orientation,
orientationName=(orientationDeg==90||orientationDeg==-90)?'Landscape':'Portrait';
options.onorientationchange&&options.onorientationchange(orientationName, orientationDeg);
};
this.start=function(){
window.ondevicemotion=ondevicemotion;
window.onorientationchange=onorientationchange;
};
this.stop=function(){
window.ondevicemotion=null;
window.onorientationchange=null;
};
};
function updateInputField(el, value){
el.value=value;
value+=10;
el.setAttribute('style','width:'+Math.round(value*25, 10)+'px');
}
function moveThing(el, acc){
acc.x=Math.round(acc.x*20);
acc.y=Math.round(acc.y*20);
acc.z=Math.round(acc.z*25);
var attr='-webkit-transform:translate3d('+acc.x+'px,'+acc.y+'px,'+acc.z+'px);';
attr+='-webkit-transition-duration:0.1s';//smoother! feel free to comment out
el.setAttribute('style',attr);
}
var myAcc = new accTrackObj({
ondevicemotion:function(acc){
updateInputField(x,acc.x);
updateInputField(y,acc.y);
updateInputField(z,acc.z);
moveThing(thing2, acc);
},
fake:function(acc){
moveThing(thing1, acc);
}
});
window.onload=function(){
x=document.getElementById('x');
y=document.getElementById('y');
z=document.getElementById('z');
thing1=document.getElementById('thing1');
thing2=document.getElementById('thing2');
}
</script>
</head><body>
<div class="thing" id="thing1">I react to sudden movement</div>
<div class="thing" id="thing2">I react to orientation</div>
<form onsubmit="return false;">
<button onclick="myAcc.start()">Start</button>
<button onclick="myAcc.stop()">Stop</button>
<br><label>x<input id="x"></label>
<br><label>y<input id="y"></label>
<br><label>z<input id="z"></label>
</form>
</body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment