首页 > 解决方案 > 角度:如何使用组件中的动画旋转图像?

问题描述

我在我的地图应用程序中创建了一个名为指南针组件的组件,当我旋转地图时,我还想以编程方式旋转带有动画的指南针,我使用角度动画,

从'@angular/core'导入{组件,OnInit,OnDestroy,输出,输入,EventEmitter,ViewChild,AfterViewInit,ElementRef};从'@angular/animations'导入{触发器、过渡、状态、动画、样式、关键帧};从'../utils/util.service'导入{ UtilService };

@Component({
  selector: "app-compasstool",
  template: require("./compasstool.component.html"),
  styles: [require("./compasstool.component.scss")],

  animations: [
    trigger('flyInOut', [
      state('start', style({ transform: 'rotate(0rad)' })),
      state('end', style({ transform: 'rotate(0.9rad)' })),
      transition('* => start', [
        animate("5s", keyframes([
          style({ transform: 'rotate(0rad)' }),// offset = 0         
        ]))
      ]),
      transition('* => end', [
        animate("2s", keyframes([
          style({ transform: 'rotate(0rad)' }),// offset = 0
          style({ transform: 'rotate(0.2rad)' }), // offset = 0.33
          style({ transform: 'rotate(0.6rad)' }), // offset = 0.66
          style({ transform: 'rotate(0.9rad)' }) // offset = 1
        ]))
      ]),
    ]),
  ],


})

我会得到半径的地图旋转,当你给组件时,它只会在初始时间起作用。我将如何在组件内调用带有旋转的动画?

标签: angulartypescriptangular-animations

解决方案


您的 component.ts 将是,

@Component({
  selector: "app-compasstool",
  template: require("./compasstool.component.html"),
  styles: [require("./compasstool.component.scss")],
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(-360deg)' })),
            transition('rotated => default', animate('2000ms ease-out')),
            transition('default => rotated', animate('2000ms ease-in'))
        ])
    ]
})
export class AppComponent {

    state: string = 'default';

    rotate() {
        this.state = (this.state === 'default' ? 'rotated' : 'default');
    }

}

而 component.html 将是,

<h1>Angular image rotation example</h1>
<button (click)="rotate()">Press me to rotate</button>

<hr>
<br><br><br><br>

<!-- Remember to add binding to tag -->
<img [@rotatedState]='state' src="https://images-na.ssl-images-amazon.com/images/I/513hBIizJUL._SY355_.jpg" >

推荐阅读