【问题标题】:Smooth DeviceOrientation Values平滑设备方向值
【发布时间】:2015-11-24 09:18:13
【问题描述】:

我正在尝试根据设备方向移动图像。但是这些值在静止时非常跳跃,在 -1 到 +2 之间没有移动,我需要一种方法来使其平滑一点。

有没有一种简单的方法可以通过平均或其他方法来减少这种紧张?

 init();
    var count = 0;

    function init() {
      if (window.DeviceOrientationEvent) {


        window.addEventListener('deviceorientation', function(eventData) {
          // gamma is the left-to-right tilt in degrees, where right is positive
          var tiltLR = eventData.gamma;

          // beta is the front-to-back tilt in degrees, where front is positive
          var tiltFB = eventData.beta;

          // alpha is the compass direction the device is facing in degrees
          var dir = eventData.alpha

          // call our orientation event handler
          deviceOrientationHandler(tiltLR, tiltFB, dir);
          }, false);
      } 
    }

    function deviceOrientationHandler(tiltLR, tiltFB, dir) {

      var logo = document.getElementById("imgLogo");
      logo.style.webkitTransform = "rotate("+ tiltLR +"deg) rotate3d(1,0,0, "+ (tiltFB*-1)+"deg)";
      logo.style.MozTransform = "rotate("+ tiltLR +"deg)";
      logo.style.transform = "rotate("+ tiltLR +"deg) rotate3d(1,0,0, "+ (tiltFB*-1)+"deg)";
    }

http://codepen.io/picard102/pen/zvOVLx

【问题讨论】:

    标签: javascript device-orientation uideviceorientation


    【解决方案1】:

    使用CSS transitions 平滑设置CSS 值。

    您可以尝试将transition: all 0.5s;-webkit-transition: all 0.5s; 添加到您的徽标中。这将导致浏览器从一个转换状态平滑过渡到下一个转换状态。

    您可能需要对该设置进行一些试验;如果您对 CSS 转换的结果不满意,您可能不得不实现自己的平滑(在 JavaScript 中,使用 JavaScript-based animation)。

    【讨论】:

    • 是的,我尝试使用过渡来平滑它,但是设备值如此快速传入所产生的噪音是真正的猪。粉丝们几乎立刻就沸腾了。
    • 你在什么设备上?我以为你在用手机。 Fwiw,您可以存储收到的事件中的值,并且每秒仅更新 30 或 60 帧,并平滑这些值(您必须自己实现)。
    • Chrome 桌面 MacBook。在 iPhone 上也能得到类似的结果。
    • 您可能想搜索游戏编程主题,例如控制器输入值的平滑;可能有现成的可用算法/库。 (从数学上讲,您正在寻找移动平均线的指数平滑:en.m.wikipedia.org/wiki/Exponential_smoothing
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多