JSFiddle - React, Tailwind, and code Playground
by eprouver
HTML
<canvas id="test" width="700" height="1000"></canvas>
JavaScript
function drawhex(ctx, size, Xcenter, Ycenter, fill){
// hexagon
var numberOfSides = 6;
ctx.beginPath();
ctx.moveTo (Xcenter + size * Math.cos(0), Ycenter + size * Math.sin(0));
for (var i = 1; i <= numberOfSides;i += 1) {
ctx.lineTo (Xcenter + size * Math.cos(i * 2 * Math.PI / numberOfSides), Ycenter + size * Math.sin(i * 2 * Math.PI / numberOfSides));
}
ctx.strokeStyle = '#fff';
ctx.fillStyle = fill;
ctx.lineWidth = 4;
ctx.stroke();
ctx.fill();
}
var ctx = document.getElementById('test').getContext('2d');
var x, y;
var height = 60;
var rows = ctx.canvas.width / height;
var cols = ctx.canvas.height / height;
var total = rows * cols;
var hexs = [];
var colors = ['#000', '#777', '#eee'];
for(var i = 0; i < total; i++){
x = (i% 7) * height * 3 + (~~(i / 7) % 2? 0: height * 1.5);
y = ~~(i / 7) * height * 0.88;
drawhex(ctx, height,x, y, colors[~~(Math.random() * colors.length)]);
hexs.push({
x: x,
y: y
});
};
setInterval(function(){
var h = hexs[~~(Math.random() * hexs.length)];
drawhex(ctx, height,h.x, h.y, colors[~~(Math.random() * colors.length)]);
}, 100)