单击按钮后,如何防止 requestAnimationFrame 重绘 canvas 次以上?

How to prevent requestAnimationFrame from redrawing canvas more then one time after clicking the button?

我正在画 canvas 罪并给它添加运动

export class CanvasComponent implements OnInit {
  @ViewChild('canvas', { static: true })
  canvas: ElementRef<HTMLCanvasElement>;

  ctx: CanvasRenderingContext2D;

  winddrawvalue = 0;
  windvalue = 0;

  constructor() { }

  @Input() set speeddata(speed: number){
    this.windvalue = speed;
    this.drawWind();
  }

  ngOnInit(): void {
    this.ctx = this.canvas.nativeElement.getContext('2d');
  }

  drawWind() {
    requestAnimationFrame(this.drawWind.bind(this));
    const canvas = this.canvas.nativeElement;
    this.ctx.lineWidth = 2;
    this.ctx.clearRect(0, 0, canvas.width, canvas.height);
    this.ctx.beginPath();

    this.ctx.moveTo(-10, canvas.height / 2 - 12);
    for (let i = 0; i < canvas.width; i++) {
      this.ctx.lineTo(i, canvas.height / 2 - 12 + Math.sin(i * 0.04 + this.winddrawvalue) * 15);
    }

    this.ctx.moveTo(-10, canvas.height / 2);
    for (let i = 0; i < canvas.width; i++) {
      this.ctx.lineTo(i, canvas.height / 2 + Math.sin(i * 0.04 + this.winddrawvalue) * 15);
    }

    this.ctx.moveTo(-10, canvas.height / 2 + 12);
    for (let i = 0; i < canvas.width; i++) {
      this.ctx.lineTo(i, canvas.height / 2 + 12 + Math.sin(i * 0.04 + this.winddrawvalue) * 15);
    }

    this.ctx.stroke();
    this.winddrawvalue += this.windvalue;
  }

}

每次我按下按钮再次绘制它时 canvas 正在重新绘制它,但它的移动速度比以前快 2 倍。 我试过

request = requestAnimationFrame(this.drawWind.bind(this));

  @Input() set speeddata(speed: number){
    this.windvalue = speed;
    this.stopAnimation(this.request);
    this.drawWind();
  }

  stopAnimation(req) {
    cancelAnimationFrame(req);
  }

cancelAnimationFrame() 希望它会获得 requestID 以停止正在进行的动画,但没有成功。

由于 drawWind 每次调用时都会设置下一个调用,因此当您从点击处理程序调用它时,现在您有两个并行的系列 运行 和事情速度加倍。

您说您尝试了 cancelAnimationFrame 但没有向我们展示该代码。这确实是你处理这个问题的方式:

drawWind() {
  cancelAnimationFrame(this.rafHandle);
  this.rafHandle = requestAnimationFrame(this.drawWind.bind(this));

现在,当按钮点击调用 drawWind 时,它已安排 rAF 回调,它会取消该回调并设置一个新回调。所以你仍然只有一个系列 运行.