Angular动画:点击图像旋转180度

12

如何使用Angular 4在图像按钮上实现图像旋转(点击:0°-> 180° / 再次点击:180°-> 0°)?

我也使用了Angular Material。

这是我的按钮:

 <!-- Button open left menubar -->
<button md-icon-button class="left-menubar-button"  (click)="start.toggle()">
  <md-icon class="md-custom-theme-gray">label_outline</md-icon>
</button>

这个按钮会打开一个侧边栏,我希望能够通过动画使其更加用户友好。

谢谢

1个回答

37

你不需要材料,因为Angular具有内置的动画效果。以下是一个例子:

import { Component } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  animations: [
      // Each unique animation requires its own trigger. The first argument of the trigger function is the name
      trigger('rotatedState', [
        state('default', style({ transform: 'rotate(0)' })),
        state('rotated', style({ transform: 'rotate(-180deg)' })),
        transition('rotated => default', animate('1500ms ease-out')),
        transition('default => rotated', animate('400ms ease-in'))
      ])
  ]
})

export class AppComponent {
    state: string = 'default';
    rotate() {
        this.state = (this.state === 'default' ? 'rotated' : 'default');
    }
}
    

并且在模板中:

<button (click)="rotate()">Press me to rotate</button>

确保将绑定添加到您正在操作的标记:

<img [@rotatedState]='state' />

此外,确保像这样将动画模块导入到您的应用程序中:

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  ...,
  imports: [
    ...,
    BrowserAnimationsModule
  ],
  ...
})

查看带有工作示例的StackBlitz


能否将图像旋转四个方向?你能告诉我如何实现吗? - U rock
你的意思是进行完整的旋转,使图像回到起始位置吗? - Lucas
2
将"rotate(-180deg)"简单地改为"rotate(-360deg)"即可完成完整旋转。如果此回答对您有帮助,请点赞 :) - Lucas
谢谢您的回答,但用户可以旋转不稳定的图像,我们需要大约4个状态(90,180,270,360度),类似于https://dev59.com/p2Qn5IYBdhLWcg3we3LD。 - U rock
如何保存旋转后的图像? - Loutocký

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接