JSFiddle - React, Tailwind, and code Playground
by Sergei Sokolov
CSS
canvas {
border: 1px solid black;
}
JavaScript
/**
* для вопроса https://qna.habr.com/q/1028270
* Сделать сетку из ромбиков, как?
*/
const ctx = document
.querySelector('canvas')
.getContext('2d');
ctx.translate(150, 75); // (0, 0) в центр
const dx = 25;
const dy = 15;
const rombus = (cx, cy, fillStyle = 'red', strokeStyle = 'grey') => {
ctx.save();
ctx.fillStyle = fillStyle;
ctx.strokeStyle = strokeStyle;
ctx.translate(cx, cy);
ctx.beginPath();
ctx.moveTo(-dx, 0);
ctx.lineTo(0, -dy);
ctx.lineTo(dx, 0);
ctx.lineTo(0, dy);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.restore();
}
const build = (side) => {
const result = [];
for (let row = -(side - 1); row <= side - 1; row++) {
const y = dy * row;
const length = side - Math.abs(row);
for (let col = -(length - 1); col <= length - 1; col += 2) {
const x = dx * col;
rombus(x, y, Math.random() > 0.48 ? 'red' : 'white');
result.push({
x,
y
});
}
}
return result;
}
const coords = build(4);
const wait = new Array(coords.length).fill(0);
const fill = new Array(coords.length).fill(0);
const render = () => {
ctx.clearRect(0, 0, 300, 150);
coords.forEach((r, i) => rombus(r.x, r.y, fill[i] ? 'red' : 'white'))
}
setInterval(() => {
fill.forEach((r, i) => {
if (--wait[i] > 0) return;
wait[i] = Math.ceil(6 * Math.random());
fill[i] = Math.random() > 0.53;
render();
});
}, 320);