Canvas fillRect() 在两次迭代后停止工作

Canvas fillRect() stops working after two iterations

我看到了一个有趣的创意数学绘图脚本,它使用幂结果的模,并想用它进行试验,迭代地改变模。

这里我们绘制了一个 256x256 的图案,然后在一段时间后更改模值并重新绘制(为简单起见,只是在两个值之间切换模值以尝试调试问题)。

它只绘制了两次迭代,显然 Canvas 停止更新,我们陷入了第二个模式。我认为 context.clearRect() 可能会解决它,但没有任何区别。该函数保留 运行 因为我得到 console.debug() 输出但没有任何视觉更新。

我在 Chrome 和 Safari

中的结果相同

我做错了什么?

https://jsbin.com/zacoperuho/edit?html,console,output

<canvas id="container"></canvas>
<script>
  container.width = 1024;
  container.height = 1024;
  const context = container.getContext("2d");
  var modulo = 9;
  
  function draw(){
    context.clearRect(0, 0, context.width, context.height);
    console.debug("modulo " + modulo)
    for (let x = 0; x < 256; x++) {
      for (let y = 0; y < 256; y++) {      
        if ((x ^ y) % modulo) {
          context.fillRect(x*4, y*4, 4, 4);
        }
      }
    }
    if(modulo == 9){
      modulo = 7;
    } else {
      modulo = 9;
    }      
    
  }
  
  draw();
  setInterval(draw, 5000);
</script>

你说得对,你需要清除 canvas 的上下文,context.clearRect 是常规方法。

问题是您提供给它的参数:context.width, context.height 常量 context 设置为 getContext("2d") 因此它是一个实例 CanvasRenderingContext2D。此接口不提供任何称为宽度或高度的属性。相反,您需要查询 Canvas 元素本身的宽度和高度。

所以简单地改变

context.clearRect(0, 0, context.width, context.height);

context.clearRect(0, 0, container.width, container.height);