性能:通过数组循环更新位置

时间:2016-02-11 05:04:53

标签: javascript angularjs cordova

我正在开发一个相对简单的Cordova应用程序,并且我试图根据设备方向在屏幕周围放置元素。

我正在倾听方向的变化并发起一次事件:

window.addEventListener('deviceorientation', function(e) {
  doTheThings(e.alpha);
});

$scope.doTheThings(d) {
  for (var i = 0; i < $scope.myThings.length; i++) {
    // I've calculated their bearing to the user already. myThings is an array of objects.

    var compass = $scope.myThings[i].bearing - degree;
    if (compass < 0) {
        compass = 360 + compass;
    } else if (compass > 360) {
        compass = ((compass / 360) - 1) * 360;
    }

    var top = 0;
                var left = 0;

                // TOP if 315 - 44 (LEFT SET)
                if (compass > 314 || compass <= 44) {
                    if (compass > 314) {
                        left = ((compass - 315) / 45) * halfCanvas;
                    } else {
                        left = ((compass / 45) * halfCanvas) + (halfCanvas);
                    }
                } else if (compass > 44 && compass <= 134) {
                    left = canvasMaxWidth;
                    top = ((compass - 45) / 90) * canvasMaxHeight;
                } else if (compass > 134 && compass <= 224) {
                    top = canvasMaxHeight;
                    left = (1 - ((compass - 135) / 90)) * canvasMaxWidth;
                } else if (compass > 224 && compass <= 314) {
                    top = (1 - ((compass - 225) / 90)) * canvasMaxHeight;
                }
                $scope.$apply(function() {
                    $scope.myThings[i].positioned = true;
                    $scope.myThings[i].top = top;
                    $scope.myThings[i].left = left;
                });

  } 
}

它不是非常复杂的代码,它完成了工作。我按如下方式在DOM中显示项目:

<div ng-repeat="thing in myThings" style="transform: translate3d({{ thing.left }}px, {{ thing.top }}px, 0px);">
  Yay!
</div>

在功能强大的设备(My Nexus 6P和Nexus 5)上使用它,但使用15个对象减慢一点,但实际上是在较慢设备(例如iPhone 4s)上的幻灯片放映。它可能每隔几秒渲染一次 - 完全残酷和不可接受。

我想我可能在这里做错了,并且有一种方法可以以某种方式优化它。有什么帮助吗?

0 个答案:

没有答案