# Angular 搭配 css 做動畫 - II ( 依照方向移動 ) ###### tags: `Angular` ## TS ### 變數宣告 ``` isHasSlot: boolean = false; top: number = 0; left: number = 0; degree: number = 0; transition: number = 0; ``` ### Robot 圖基本移動動畫 / style 指定位置 ``` robotMoveWithAnimation(targetLeft: number, targetDegree: number, hasSlot: boolean) { this.top = this.aligner.nativeElement.offsetHeight - 20; // 避免跑位 this.transition = 0.5; if (this.left == targetLeft) { this.degree = targetDegree; } // 現在位置在右邊的話,先向左轉 else if (this.left > targetLeft) { this.degree = 90; } // 現在位置在左邊的話,先向右轉 else { this.degree = 270; } // 先移動到正確的位置 setTimeout(() => { this.transition = 1; this.left = targetLeft; }, 500) // 再轉到目標的方向 setTimeout(() => { this.transition = 0.5; this.degree = targetDegree; }, 1000) // 等圖片A停好後更換圖片B setTimeout(() => { this.isHasSlot = hasSlot; }, 1500) } robotMovePosition() { return { "position": "absolute", "top": `${this.top}px`, "left": `${this.left}px`, "transition": `${this.transition}s`, "transform": `rotate(${this.degree}deg)`, "z-index": "999", }; } ``` ### Robot 移動操作 ``` robotGoLP() { this.robotInWhereMachine = `loadport_${this.selectLP}`; let offSetLeft = 70; // 調整成適當位置 if (this.selectLP == 1) { offSetLeft += this.loadport_1.nativeElement.offsetLeft; } if (this.selectLP == 2) { offSetLeft += this.loadport_2.nativeElement.offsetLeft; } if (this.selectLP == 3) { offSetLeft += this.loadport_3.nativeElement.offsetLeft; } if (this.selectLP == 4) { offSetLeft += this.loadport_4.nativeElement.offsetLeft; } this.robotMoveWithAnimation(offSetLeft, 180, false) } robotGoAlignerPosition() { this.robotInWhereMachine = "aligner"; const targetLeft = this.aligner.nativeElement.offsetLeft + 200; // 200 為了在該 div 靠右 this.robotMoveWithAnimation(targetLeft, 90, true) } ``` ## HTML ``` <img *ngIf="!isHasSlot" [ngStyle]="robotMovePosition()" src="/assets/Images/robot-t_no_slot.png" width="100" height="100"> <img *ngIf="isHasSlot" [ngStyle]="robotMovePosition()" src="/assets/Images/robot-t1_has_slot.png" width="100" height="100"> ``` ## 結果 ![](https://i.imgur.com/EHBVLFD.gif) ## 使用圖片 ![](https://i.imgur.com/7NVsHYz.png) ![](https://i.imgur.com/hfIiSGz.png)