user3599649
user3599649

Reputation: 11

Avoiding Javascript Memory Leaks from the Creation of Canvas

I have some HTML and Javascript code that draws a 2D canvas in the page. In the task manager, I can see memory increasing rapidly until the web page freezes.

Please let me know how I can prevent memory leaks or provide me with some alternative code that is able to draw canvas on the browser without creating such leaks.

function setup() {
  // insert setup code here
}

function draw() {
    // insert drawing code here
    var canvas = document.createElement('canvas');
    canvas.id     = "CursorLayer";
    canvas.width  = 1224;
    canvas.height = 600;
    canvas.style.zIndex   = 8;
    canvas.style.position = "absolute";
    canvas.style.border   = "1px solid";

    document.body.appendChild(canvas);
 
    var c2 = canvas.getContext('2d');
 
    var centerX=canvas.width/2-100;
    var centerY=canvas.height/2-100;
 
    c2.fillStyle = '#696969';
    c2.beginPath();
    c2.moveTo(centerX, centerY);
    c2.lineTo(centerX+200,centerY);
    c2.lineTo(centerX+200, centerY+200);
    c2.lineTo(centerX, centerY+200);
    c2.closePath();
    c2.fill();

    // adding source location

    var ctx = canvas.getContext("2d");
    ctx.fillStyle = '#008000';

    ctx.beginPath();
    ctx.arc( 20, canvas.height-20, 10, 0, 2 * Math.PI);
    ctx.stroke();
    ctx.closePath();
    ctx.fill();

    // adding destination location
  	
    var ctx1 = canvas.getContext("2d");
    ctx1.fillStyle = '#f00';

    ctx1.beginPath();
    ctx1.arc( canvas.width-20, 20, 10, 0, 2 * Math.PI);
    ctx1.stroke();
    ctx1.closePath();
    ctx1.fill();
}
<!DOCTYPE html>
<html>
    <head>
	<title>Robot Path Planning</title>
            <style>
	        body {
		    padding: 0;
                    margin: 0;
		}
	    </style>
	    <script src="../p5.min.js"></script>
	    <script src="../addons/p5.dom.min.js"></script>
	    <script src="../addons/p5.sound.min.js"></script>
	    <script src="sketch.js"></script>
        </head>
    <body>
    </body>
</html>

Browser Memory consumption

Upvotes: 1

Views: 1612

Answers (1)

6502
6502

Reputation: 114579

Apparently your code is creating a new canvas entity for each draw call and this doesn't make sense.

You should instead create the canvas only once and then just do drawing on it in the draw call. If you need to clear the previous frame you can just reset the width/height properties or call clearRect.

Upvotes: 3

Related Questions