简体   繁体   中英

Moving a box to a random position with angularjs

I am looking for a way to implement the exact functionality from this answer using angularjs: Specifically, for a box (div) to move randomly around a screen, while being animated. Currently I have tried

myApp.directive("ngSlider", function($window) {
  return {
    link: function(scope, element, attrs){
        var animateDiv = function(newq) {
            var oldRect = element.getBoundingClientRect();
            var oldq = [oldRect.top, oldRect.left];
            if (oldq != newq){
                var dir = calcDir([oldq.top, oldq.left], newq);
                element.moveTo(oldq.left + dir[0], oldq.top + dir[1]);
                setTimeout(animateDiv(newq), 100);
            }
        };

        var makeNewPosition = function() {
            // Get viewport dimensions (remove the dimension of the div)
            var window = angular.element($window);
            var h = window.height() - 50;
            var w = window.width() - 50;

            var nh = Math.floor(Math.random() * h);
            var nw = Math.floor(Math.random() * w);

            return [nh,nw];

        };


        function calcDir(prev, next) {
            var x = prev[1] - next[1];
            var y = prev[0] - next[0];
            var norm = Math.sqrt(x * x + y * y);
            return [x/norm, y/norm];
        }
        var newq = makeNewPosition();
        animateDiv(newq);
    }
  };
});

There appears to be quite a bit wrong with this, from an angular point of view. Any help is appreciated.

I like to take advantage of CSS in situations like this.

  • absolutely position your div
  • use ng-style to bind top and left attributes to some in-scope variable
  • randomly change the top and left attributes of this in-scope variable
  • use CSS transitions on top and left attributes to animate it for you

I made a plnkr ! Visit Kentucky!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM