1. 陀螺仪deviceorientation的使用,参考《关于陀螺仪deviceorientation》https://segmentfault.com/a/1190000007183883 。
2. transform各属性的具体使用,参考《深入理解CSS变形transform(3d)》https://www.cnblogs.com/xiaohuochai/p/5351477.html 。
3. 代码实现在规定Safari横屏的前提下,图片相对观察点旋转的效果。
var x = 0,y = 0,rotateRes = ""; //横屏时X轴与gamma对应,Y轴与beta对应,
var oriB = 0, oriG = window.orientation>0 ? -45 : 45; //横屏时orientation=90/-90,根据方向设定原始original gamma
var lastB = 0 , lastG = oriG; //上一次记录的beta[-180,180)/gamma[-90,90)
var curB = 0, curG = oriG;//当前的current beta/gamma
if (window.DeviceOrientationEvent) { //判断当前设备是否支持事件
window.addEventListener("deviceorientation", orientationHandler, false);
function orientationHandler(event) {
curG = Math.round(event.gamma);
curB = Math.round(event.beta);
if(Math.abs(curB-oriB)<60) { //只在允许的范围内进行旋转
if(Math.abs(curG-oriG)<60 && Math.abs(curG-lastG) < 100 ) { //与初始平面不超过60度,且不过分界点才旋转
x += curG-lastG; //若希望图片反向旋转,可改为 x -= ...
lastG = curG;
}
}
if(Math.abs(curB-oriB)<60 && Math.abs(curB-lastB) < 200 ) {
y += curB-lastB;
lastB = curB;
}
rotateRes = "perspective(1200px) rotateX(" + x +"deg) rotateY("+ y +"deg)"; //perspective为视距,即人眼到屏幕的距离
$("#rotate-image").css({transform:rotateRes,'-webkit-transform':rotateRes});
}
}
else {
console.log("对不起,您的设备还不支持Device Orientation!!!");
}