Prevent an element to rotate itself in a circular CSS3 animation

前端 未结 2 1276
面向向阳花
面向向阳花 2020-12-29 13:32

Ok so this is really getting frustrated for me here, first of all if my question framing is wrong please do edit it(if you think so)...and ok, as my screens will explain you

相关标签:
2条回答
  • 2020-12-29 14:28

    I've just written a pure JavaScript implementation for those who do not want to use CSS 3 animations (e.g. for compatibility reasons).

    Demo

    // requestAnim shim layer by Paul Irish
    window.requestAnimFrame = (function(){
      return  window.requestAnimationFrame       || 
              window.webkitRequestAnimationFrame || 
              window.mozRequestAnimationFrame    || 
              window.oRequestAnimationFrame      || 
              window.msRequestAnimationFrame     || 
              function(/* function */ callback, /* DOMElement */ element) {
                window.setTimeout(callback, 1000 / 60);
              };
    })();
    
    function CircleAnimater(elem, radius, speed) {
        this.elem = elem;
        this.radius = radius;
        this.angle = 0;
        this.origX = this.elem.offsetLeft;
        this.origY = this.elem.offsetTop;
        
        this.shouldStop = false;
        this.lastFrame = 0;
        this.speed = speed;
    }
    
    CircleAnimater.prototype.start = function () {
        this.lastFrame = +new Date;
        this.shouldStop = false;
        this.animate();
    }
        
    CircleAnimater.prototype.stop = function () {
        this.shouldStop = true;
    }
        
    CircleAnimater.prototype.animate = function () {
        var now    = +new Date,
            deltaT = now - this.lastFrame;
        
        var newY = Math.sin(this.angle) * this.radius;
        var newX = Math.cos(this.angle) * this.radius;
    
        this.elem.style.left = (this.origX + newX) + "px";
        this.elem.style.top = (this.origY + newY) + "px";
        this.angle += (this.speed * deltaT);
    
        this.lastFrame = +new Date;
    
        if (!this.shouldStop) {
            var $this = this;
            requestAnimFrame(function () {
                $this.animate();
            });
        }        
    }
    
    0 讨论(0)
  • 2020-12-29 14:33

    Position it absolutely, don't change the transform-origin, leave it at 50% 50%.

    Then simply rotate the element, translate it by the value of the radius and then cancel the first rotation - you can see how chaining transforms works here.

    @keyframes rot {
      0% { transform: rotate(0deg) translate(150px) rotate(0deg); }
      100% { transform: rotate(360deg) translate(150px) rotate(-360deg); }
    }
    

    demo

    0 讨论(0)
提交回复
热议问题