You can get the base64 version of your image using the toDataURL() method of the canvas element.
From there it's as simple as setting the background-image of your page to the string "url(" + base64 + ")"
$(document).ready(function(){
var canvas = document.getElementById('dkBg');
var ctx = canvas.getContext('2d');
ctx.canvas.width = 64; //window.innerWidth;
ctx.canvas.height = 64; //window.innerHeight;
ctx.fillStyle = 'rgb(0,0,0)';
//I want the following rectangle to be repeated:
ctx.fillRect(0,0,64,64);
for(var w=0; w<=64; w++){
for(var h=0; h<=64; h++){
rand = Math.floor(Math.random()*50);
while(rand<20){
rand = Math.floor(Math.random()*50);
}
opacity = Math.random();
while(opacity<0.5){
opacity = Math.random();
}
ctx.fillStyle= 'rgba('+rand+','+rand+','+rand+','+opacity+')';
ctx.fillRect(w,h,1,1);
}
}
document.documentElement.style.backgroundImage =
'url(' +canvas.toDataURL() + ')';
});
Note that you need to make the canvas 64x64 because that's the size of your source image.
You can also now make the canvas display:none, or even remove it from the dom completely because it's only acting as a source for the background-image.
Also, what on earth is up with those while loops?
while(rand<20){
rand = Math.floor(Math.random()*50);
}
It looks like you're trying to enforce a minimum value. Just use this:
rand = Math.floor(Math.random() * (50-20) + 20);