문제

I've been playing around with JS+CSS animations for the first time. I am trying to rotate a div (or a bunch of them independently) with these random factors:

  • Random direction
  • Random degrees
  • With random pauses

I managed to gather this script , which worked well. It rotates a div with id="square" infinity, into a [random] direction, by [random] degrees

    function redo() {  
    $.fn.animateRotate = function(angle, duration, easing, complete) {
            return this.each(function() {
            var $elem = $(this);

            $({deg: 0}).animate({deg: angle}, {
                duration: duration,
                easing: easing,
                step: function(now) {
                    $elem.css({
                        transform: 'rotate(' + now + 'deg)'
                    });
                },
                complete: complete //|| $.noop
            });
        });
    };
    plusOrMinus = Math.random() < 0.5 ? -1 : 1;
    randAngle = Math.floor(Math.random()*70+30) * plusOrMinus;
    randDelay = Math.floor(Math.random()*3000+2000);
    $('#square').animateRotate(randAngle);
    timer = setTimeout(function() { redo(); },randDelay);
}

redo();

http://jsfiddle.net/NWLVY/1

Now I've been having a few difficulties:

  1. I would like to pass more than one element into this loop, and I want them to behave independently. I wouldn't mind if they all had the same class, or if I just needed to write multiple lines to execute each one. There won't be too many.
  2. This rotation doesn't continue from the last angle. It keeps jumping back. I can't figure out how to fix this.
  3. I can't seem to pass any easing options like swing or linear, nor any other options such as duration and complete
도움이 되었습니까?

해결책

Solved.

I used a slightly different script but it now works. I added Transition and Animation lines to the CSS of the rotating element,

transition:2s;
animation:ease-in-out;

Those seemed to have fixed the issue for the jagged spinning, and let me add some easing. Then I used a wrapping function to pass different elements through the function.

<Script>
 function rotate (elementID) {

    var $rota = $(elementID),
        degree = 0,
        timer;

    function spin() {    
        $rota.css({ transform: 'rotate(' + degree + 'deg)'});   // rotate element
        plusOrMinus = Math.random() < 0.5 ? -1 : 1;       // random spin direction
        randAngle = Math.floor(Math.random()*70+50) * plusOrMinus; // random degrees
        randDelay = Math.floor(Math.random()*1000+2000);  //random delay
        timer = setTimeout(function() {  // set delay
            degree += randAngle;  // add random degree to current variable
            spin(); // loop it
        },randDelay);
    }

    spin();    // start first spin for element

};

rotate ('#square'); // run it
rotate ('#square2'); // run it again

</script>

Here it is at work http://jsfiddle.net/NWLVY/2/

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top