2012-12-27 50 views
9

好的,這真的讓我感到沮喪,首先,如果我的問題框架是錯誤的,請編輯它(如果你這麼認爲)...並確定,因爲我的屏幕會解釋你,但我仍然希望我的元素應該保持特定的形狀,不要隨着動畫一起旋轉,我錯過了一些非常愚蠢的事情?防止元素在圓形CSS3動畫中自行旋轉

我想要的東西

What I Want

發生了什麼

What's Happening

jQuery的解決方案,歡迎(但我很想CSS3解決方案)

注意:不要去對元素的不透明度用油漆和 其他與Photoshop,什麼事的是方應旋轉,廣場 形狀,1是由

HTML

<div><span></span></div> 

CSS

@keyframes round_round { 
    from { 
     transform: rotate(0deg); 
    } 
    to { 
     transform: rotate(360deg); 
    } 
} 

div { 
    width: 50px; 
    height: 50px; 
    animation: round_round 3s linear infinite; 
    margin: 50px auto 0; 
    transform-origin: 50% 150px; 
    background-color: #8FC1E0; 
} 

span { 
    display: inline-block; 
    margin: 5px; 
    height: 5px; 
    width: 5px; 
    background: #c00000; 
} 

Demo

回答

16

絕對的位置,不要改變transform-origin,讓它在50% 50%

然後只需旋轉元素,將其轉化爲半徑值,然後取消第一次旋轉 - 您可以看到鏈式變換如何工作here

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

demo

+0

現在這樣的作品,真棒......順便說一句只是確保你在你的答案(http://jsfiddle.net/s7Bsn/3/)加一把小提琴,順便說一句沒有必要'絕對' –

2

我剛寫了一個純JavaScript實現對於那些不想使用CSS 3個動畫誰(例如由於兼容性原因)。

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

所有現代瀏覽器都支持CSS3轉換(自9以來支持IE) - http://caniuse.com/transforms2d。對RAF的支持更糟糕(儘管你提供了一個回退):http://caniuse.com/requestanimationframe –

+2

@RobW我只寫過,因爲我喜歡那種動畫。這只是爲了好玩。當然,我知道CSS(3)的東西總是更優雅的解決方案在JS中實現;) – ComFreek

+1

@ComFreek,這是很酷的兄弟,+1,謝謝你;) –