# Angular 搭配 css 做動畫 ( UFO 圖範例 ) ###### tags: `Angular` ## 說明 1. 使用透明背景 PNG 圖 or GIF 圖 2. 使用 ngClass 和 ngStyle 設置變數 or function 來讓程式控制渲染 3. 按按鈕的時候更改相關變數內容,從而達到移動/動畫的效果 4. ngClass => Anmimation 作為圖片本身晃動動作;ngStyle => Transition 作為圖片移動控制 ## HTML ![](https://i.imgur.com/0aSneIM.png) ``` <img [ngClass]="robotAnimation" [ngStyle]="moveRobotPosition()" src="/assets/ufo.png" width="50" height="50"> ``` ## CSS ``` .float-robot-animation { animation-name: upAnimation; transform-origin: center bottom; animation-duration: 1s; animation-fill-mode: both; animation-iteration-count: infinite; animation-delay: .5s; } @keyframes upAnimation { 0% { transform: rotate(6deg); } 10% { transform: rotate(-12deg); } 20% { transform: rotate(12deg); } 28% { transform: rotate(-10deg); } 36% { transform: rotate(10deg); } 42% { transform: rotate(-8deg); } 48% { transform: rotate(8deg); } 52% { transform: rotate(-4deg); } 56% { transform: rotate(4deg); } 60% { transform: rotate(0deg); } 100% { transform: rotate(0deg); } } ``` ## TS ![](https://i.imgur.com/6wKaVyW.png) ``` // 宣告必要變數 top: number = 0; left: number = 0; robotInWhereMachine: string = ""; robotAnimation = "" // Class ( Animation Control ) moveRobotAnimation() { this.robotAnimation = "float-robot-animation"; setTimeout(() => { this.robotAnimation = "" }, 1000) } // Style ( Position Control ) moveRobotPosition() { return { position: "absolute", top: `${this.top}px`, left: `${this.left}px`, transition: "1s", }; } // 按鈕動作 robotBackOriginalPosition() { this.robotInWhereMachine = ""; this.top = 0; this.left = 0; this.moveRobotAnimation(); } robotGoAlignerPosition() { this.robotInWhereMachine = "Aligner"; this.top = this.aligner.nativeElement.offsetTop + 10; // 10 為微調 this.left = this.aligner.nativeElement.offsetLeft + 220; // 220 為了在該 div 靠右 this.moveRobotAnimation(); } ``` ## 結果 ![](https://i.imgur.com/2tDzk0X.gif) ※BTW: Aligner 區塊因是不同 Component,其顏色變更也是傳入變數做控制 ## 把結果改成 GIF 圖的效果 更有趣了一點XD,不過應該也可以用 Animation 達成上下漂浮的感覺 ![](https://i.imgur.com/TD3wSOU.gif) ## 原圖 & 參考資料 ### 原圖來源 ( 直接點圖連結 ) [![](https://i.imgur.com/msxeKHm.gif =70x70)](https://gifer.com/en/4AI9) [![](https://i.imgur.com/rnJ02CX.png =50x50)](https://www.flaticon.com/free-icon/ufo_620689) ### 參考資料 [css3 左右晃动小动画 ](https://juejin.cn/post/6844904000307855374) [CSS3 動畫 Transition, Animation, Transform 基礎 [筆記]](https://hoohoo.top/blog/css3-animation-notes/)