为什么这个画布绘图会导致内存泄漏?

Iva*_*nov 1 javascript memory-leaks html5-canvas

以下代码导致内存/CPU 泄漏 - CPU 使用率迅速增加并在几分钟内达到 100%,这对性能不利。我想了解为什么会发生这种情况,这样我以后就不会犯类似的错误了。

function drawBoard(w, h, p, context) {

  for (var x = 0; x <= w; x += 40) {
    context.moveTo(0.5 + x + p, p);
    context.lineTo(0.5 + x + p, h + p);
  }


  for (var x = 0; x <= h; x += 40) {
    context.moveTo(p, 0.5 + x + p);
    context.lineTo(w + p, 0.5 + x + p);
  }

  context.strokeStyle = "black";
  context.stroke();

}
let cancel
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
let context = ctx
function Loop() {
  cancel = window.requestAnimationFrame(Loop)
  drawBoard(800, 600, 10, context)
}
Loop() 
Run Code Online (Sandbox Code Playgroud)

enx*_*eta 6

这是因为你从不使用 context.beginPath();

这是来自 MDN:“CanvasRenderingContext2D.beginPath() 的 Canvas 2D API 方法通过清空子路径列表来启动新路径

function drawBoard(w, h, p, context) {

  for (var x = 0; x <= w; x += 40) {
    context.beginPath();
    context.moveTo(0.5 + x + p, p);
    context.lineTo(0.5 + x + p, h + p);
    context.stroke();
   
  }


  for (var y = 0; y <= h; y += 40) {
    context.beginPath();
    context.moveTo(p, 0.5 + y + p);
    context.lineTo(w + p, 0.5 + y + p);
    context.stroke();
  }

}
let cancel
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
let w = canvas.width = 800;
let h = canvas.height= 600;
let context = ctx
function Loop() {
  cancel = window.requestAnimationFrame(Loop);
  context.clearRect(0,0,w,h)
  drawBoard(w, h, 10, context)
}
Loop() 
Run Code Online (Sandbox Code Playgroud)
<canvas id="canvas"></canvas>
Run Code Online (Sandbox Code Playgroud)