Blog>
Snippets

Animation Performance Tracking

Leverage the Web Animations API to track performance of Angular animations, measuring frames per second (FPS) and time taken to complete the animations.
class AnimationPerformanceTracker {

  constructor() {
    this.startTime = 0;
    this.frameCount = 0;
    this.fps = 0;
  }

  startTracking() {
    // Reset counters
    this.startTime = performance.now();
    this.frameCount = 0;
    this.fps = 0;
    requestAnimationFrame(this.countFrame.bind(this));
  }

  countFrame() {
    // Increment the frame counter
    this.frameCount++;
    const currentTime = performance.now();
    const elapsedTime = currentTime - this.startTime;
    // Calculate FPS every second
    if (elapsedTime >= 1000) {
      this.fps = this.frameCount / (elapsedTime / 1000);
      console.log(`Average FPS: ${this.fps.toFixed(2)}`);
      // Reset counters after 1 second
      this.startTracking();
    } else {
      // Continuously request frames
      requestAnimationFrame(this.countFrame.bind(this));
    }
  }

}

// Usage in Angular Component
@Component({ /* ... */ })
export class YourComponent {

  // Add tracker to your component
  animationTracker = new AnimationPerformanceTracker();

  ngAfterViewInit() {
    // Start tracking when the component's view has been initialized
    this.animationTracker.startTracking();
  }

  // Apply this method to track your specific animation
  startAnimation() {
    // Define your animation here using the Web Animations API
    const animation = this.element.animate(/* keyframes */, /* timing */);
    animation.onfinish = () => {
      const totalTime = performance.now() - this.animationTracker.startTime;
      console.log(`Animation time: ${totalTime.toFixed(2)}ms`);
    };
  }

}
This code creates an AnimationPerformanceTracker class to measure frames per second (FPS) and time taken for animations in an Angular component. Use the `startTracking()` method to begin tracking and call `startAnimation()` to apply it to a specific animation using the Web Animations API. The average FPS and animation completion time are logged to the console.