JSFiddle - React, Tailwind, and code Playground
HTML
<div style="position:absolute;height:300px;width:300px;background:red;z-index:-999"></div>
<canvas id="rectangle" width="300" height="300"></canvas>
JavaScript
var canvas = document.getElementById('rectangle');
if (canvas.getContext) {
var context = canvas.getContext('2d');
context.globalAlpha = 0;
context.fillStyle = "rgb(0,0,0)";
context.fillRect(0, 0, 300, 300);
}
var imgd = context.getImageData(0, 0, canvas.width, canvas.height);
var numberOfAlphaPix = 20000; //this is the number of pixel for which you want to change the alpha channel, I let you do the job to retrieve this number as you wish
//fill an array with numbers that we'll pop to get unique random values
var rand = [];
// Loop over each pixel with step of 4 to store only alpha channel in array ( R=1 ,G=2 , B=3, A=4 )
for (var i =3 ; i < imgd.data.length; i += 4) {
rand.push(i);
}
//shuffle the array
for (var i = rand.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = rand[i];
rand[i] = rand[j];
rand[j] = tmp;
}
for (var i = 0; i < numberOfAlphaPix; i++) {
imgd.data[rand.pop()] = 255; //set alpha channel to 255
}
//context.clearRect(0, 0, 300, 300);
// Draw the ImageData object at the given (x,y) coordinates.
context.putImageData(imgd, 0, 0);