简体   繁体   中英

Why this canvas drawing is causing memory leak?

The following code is causing a memory/CPU leak - CPU usage quickly increases and reaches 100% in a few minutes, which is detrimental to performance. I want to understand why is this happening so I won't make similar mistakes in the future.

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() 

It's because you are never using context.beginPath();

This is from MDN: "The CanvasRenderingContext2D.beginPath() method of the Canvas 2D API starts a new path by emptying the list of sub-paths "

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM