const ctx = canvas.getContext("2d");
const ctx1 = canvas1.getContext("2d");
const w = canvas.width;
const h = canvas.height;
canvas.addEventListener("click",drawPoints);
canvas1.addEventListener("click",drawPoints);
function randomPoint(){
const xx = Math.floor(Math.random() * w);
const yy = Math.floor(Math.random() * h);
ctx1.fillRect(xx,yy,pointSize,pointSize);
}
function randomPointOf(n, ofM){
const spread = Math.sqrt(ofM);
const xs = w / spread; // x spacing
const ys = h / spread; // y spacing
n = n % ofM;
const x = (n % spread) * xs;
const y = (Math.floor(n / spread)) * ys;
const xx = Math.floor(Math.random() * xs + x);
const yy = Math.floor(Math.random() * ys + y);
ctx.fillRect(xx,yy,pointSize,pointSize);
}
function randomPoints(pointCount, distrabutionCount){
var i;
for(i = 0; i < pointCount; i ++){
randomPointOf(i,distrabutionCount); // do distrubuted random
randomPoint(); // do random
}
}
var pointCount = 100;
var pointSize = 1
ctx.font = ctx1.font = "12px arial";
ctx1.fillStyle = ctx.fillStyle = "black";
ctx1.strokeStyle = ctx.strokeStyle = "white";
ctx1.lineWidth = ctx.lineWidth = 3;
drawPoints();
function drawPoints(){
ctx.clearRect(0,0,w,h);
ctx1.clearRect(0,0,w,h);
pointCount *= 2;
if(pointCount > w * h){
pointCount = 100;
}
pointSize = pointCount < 1600 ? 2 : 1;
randomPoints(pointCount,100);
ctx.strokeText("Weighted. "+ pointCount + " points",10,14);
ctx1.strokeText("Random. "+ pointCount + " points",10,14);
ctx.fillText("Weighted. "+ pointCount + " points",10,14);
ctx1.fillText("Random. "+ pointCount + " points",10,14);
}
canvas {
border : 2px black solid;
}
<canvas id="canvas" width = 256 height = 256></canvas>
<canvas id="canvas1" width = 256 height = 256></canvas>
<div>Click canvas to increase point count</div>