canvas leak

by Victor

HTML

<script src="https://rawgit.com/victornpb/11202651/raw/833254dc03ab92be61aaa939bb8f50aed78fa6ec/fpsMeter.js"></script>
<script src="https://rawgit.com/victornpb/d273e04b865eeadc583e/raw/fdce1dca1ca6f21894544515326136300423b8dd/insaneLoop.js"></script>
<div>
    <button onclick="SHOULDSTOP=true">Stop</button><br>
    <span id="fps">121</span> Updates/sec
</div>
<hr>        

<canvas id="canvas"></canvas>

CSS

canvas{
    width:100%;
    height:100%;
    border: 1px solid blue;
}

window,body{
    width:100%;
    height:100%;
}

JavaScript

window.onload=function(){
    
    //setup the canvas size to the actual size.
    canvas.width = canvas.clientWidth;
    canvas.height = canvas.clientHeight;
    
    startLoop();
}

//called as fast as it can
function loop(){
    drawNoise();
}


function drawNoise(){
	var context = canvas.getContext("2d");
	var pattern = context.createPattern(generatePattern(), "repeat");
	context.rect(0,0, canvas.width, canvas.height);
	context.fillStyle = pattern;
	context.fill()
}

//create a on memory canvas to generate a tile with 64x64 pixels of noise and return it
function generatePattern(){
	
	var canvas = document.createElement("canvas");
	canvas.width = 64;
	canvas.height = 64;
	var context = canvas.getContext("2d");
		
	var image = context.getImageData(0, 0, canvas.width, canvas.height);
	var imageData = image.data; // here we detach the pixels array from DOM
    
	var p;
	var pixels = canvas.width*canvas.height;
    while(pixels--){
		p = pixels*4;
	    imageData[p+0] = Math.random() >= 0.5 ? 255 : 0; // Red
	    imageData[p+1] = Math.random() >= 0.5 ? 255 : 0; // Green
	    imageData[p+2] = Math.random() >= 0.5 ? 255 : 0; // Blue
	    imageData[p+3] = 255; // Alpha
	}
    
	image.data = imageData;
	context.putImageData(image, 0, 0);
    
	return canvas;
}



/********************************/
var SHOULDSTOP = false;
var f = fpsMeter(fps, 1);

function startLoop(){
    insaneLoop(function(){
        loop(); 
        f(); //compute fps
        return !SHOULDSTOP; //condition to break the loop
    },50,1);
}