You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将WebGL Earth旋转动画函数转为Angular TypeScript代码

WebGL Earth 旋转动画的TypeScript转换与启停实现

转换后的TypeScript代码(适配Angular组件+原地启停)

import { Component, OnInit, OnDestroy } from '@angular/core';
// 若WebGL Earth未提供官方类型,可添加声明
declare const WE: any;

@Component({
  selector: 'app-earth-globe',
  templateUrl: './earth-globe.component.html',
  styleUrls: ['./earth-globe.component.css']
})
export class EarthGlobeComponent implements OnInit, OnDestroy {
  private earth: any;
  private before: number | null = null;
  private animationId: number | null = null;
  private isAnimating = false;

  ngOnInit(): void {
    // 初始化WebGL Earth globe(根据你的实现调整)
    this.earth = new WE.map('earth_div');
    this.earth.setView([39.9042, 116.4074], 2);
  }

  // 切换动画启停状态
  toggleAnimation(): void {
    this.isAnimating ? this.stopAnimation() : this.startAnimation();
  }

  private startAnimation(): void {
    this.isAnimating = true;
    this.before = null; // 重置时间基准,确保从当前帧开始计算间隔

    const animate = (now: number) => {
      if (!this.isAnimating) return;
      
      const currentPos = this.earth.getPosition();
      const elapsed = this.before ? now - this.before : 0;
      this.before = now;

      // 更新经度实现旋转,保持纬度不变
      this.earth.setCenter([currentPos[0], currentPos[1] + 0.1 * (elapsed / 30)]);
      this.animationId = requestAnimationFrame(animate);
    };

    this.animationId = requestAnimationFrame(animate);
  }

  private stopAnimation(): void {
    this.isAnimating = false;
    if (this.animationId) {
      cancelAnimationFrame(this.animationId);
      this.animationId = null;
    }
  }

  ngOnDestroy(): void {
    // 组件销毁时自动停止动画,避免内存泄漏
    this.stopAnimation();
  }
}

关键问题解决说明

  • 类型声明规范:将原JS的var before = null改为TypeScript的private before: number | null = null,明确变量类型,通过TS类型检查
  • 递归回调处理:在组件类内部定义动画回调函数,利用类的状态变量维护动画上下文,避免原JS中可能出现的this指向问题
  • 原地启停实现:
    • 用isAnimating标记动画运行状态,控制动画循环的持续执行
    • 保存requestAnimationFrame返回的ID,通过cancelAnimationFrame精准停止动画
    • 启动动画时重置时间基准before,确保从当前位置继续旋转,不会出现跳变

内容的提问来源于stack exchange,提问作者user9284u5983u423u4o2u43

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 11:13:13