在鸿蒙应用中,Canvas 组件可以实现丰富的动态效果,适合用于动画和实时更新的场景。本篇将介绍如何在 Canvas 中实现动画循环、动态进度条、旋转和缩放动画,以及性能优化策略。

关键词
- Canvas 组件
- 动态绘制
- 动画效果
- 动态进度条
- 旋转和缩放
- 性能优化
一、使用定时器实现动画循环
通过定时更新画布内容,可以让图形在 Canvas 中产生动画效果。setTimeout 方法可用于实现帧刷新,使图形流畅移动。
1.1 动画循环示例:水平移动
以下代码展示了如何在 Canvas 上创建一个自动移动的圆形。
@Entry
@Component
struct MovingCircleExample {
   
  private x: number = 0; // 圆心的 x 坐标
  private dx: number = 5; // 每帧的水平移动距离
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(); // 创建 Canvas 渲染上下文
  build() {
   
    Column() {
   
      Canvas(this.context)
        .width('100%')
        .height(600)
        .onReady(() => {
   
          this.animateCircle(); // 开始动画
        });
    }
  }
  private animateCircle(): void {
   
    this.context.clearRect(0, 0, 600, 600); // 清除画布
    this.context.beginPath(); // 开始新路径
    this.context.arc(this.x, 300, 50, 0, 2 * Math.PI); // 绘制圆形
    this.context.fillStyle = '#FF4500'; // 设置填充颜色为橙色
    this.context.fill(); // 填充圆形
    this.x += this.dx; // 更新圆心的 x 坐标
    if (this.x > 600 || this.x < 0) {
   
      this.dx = -this.dx; // 碰到边界时反向
    }
    // 使用 setTimeout 模拟帧刷新
    setTimeout(() => this.animateCircle(), 16); // 约60帧每秒
  }
}
效果示例:一个橙色圆形在 Canvas 中水平往返移动,碰到边界会反弹。



















