为什么此画布绘图导致内存泄漏?

时间:2018-09-24 22:21:29

标签: 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() 

1 个答案:

答案 0 :(得分:3)

这是因为您从未使用过context.beginPath();

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

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() 
<canvas id="canvas"></canvas>