css3 transform + deviceorientation实现图片旋转效果

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!!!");
}

 

转载于:https://www.cnblogs.com/xquancnblogs/p/8628845.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值