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

如何清除Canvas中的Path2D路径?循环渲染动画清除失效问题

问题原因与解决办法

你遇到的clearRect()无效问题,核心原因是用错了Canvas的宽高属性——innerWidth和innerHeight并不是Canvas元素的标准属性,调用它们会返回undefined,导致clearRect()根本没有覆盖到实际的绘图区域,自然看不到清除效果。

修正后的代码

把原来的innerWidth/innerHeight替换为Canvas自身的.width和.height属性即可:

update(options) {
  // 改用canvas自身的width和height属性定位清除范围
  this.ctx.clearRect(0, 0, this.canvas.nativeElement.width, this.canvas.nativeElement.height);
  this.ctx.beginPath();
  const path = this.cardinal(options.points, true, 1); // SVG path
  const P2D = new Path2D(path);
  this.ctx.fill(P2D);
}

额外说明

  • Canvas元素的.width和.height是控制绘图上下文坐标空间的实际尺寸,和CSS设置的显示尺寸是两个独立概念,如果两者不一致会导致图形拉伸,需要注意匹配。
  • 每次更新动画前调用clearRect()清除整个画布,就能确保旧的Path2D路径不会残留,新路径可以正常渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:58:08