<canvas id="canvas"></canvas>
body, html {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
cursor: pointer;
}
/*
Johan Karlsson, 2020
https://twitter.com/DonKarlssonSan
MIT License, see Details View
*/
let canvas;
let ctx;
let w, h;
let hexagons;
let colors;
let colorSchemeIndex;
class Hexagon {
constructor(x, y, R) {
this.x = x;
this.y = y;
this.R = R;
}
draw() {
ctx.save();
ctx.translate(this.x, this.y);
let angle = Math.PI * 2 / 3;
let nrOfRotations = 3;
let a = Math.PI / 6;
for(let rot = 0; rot < nrOfRotations; rot++) {
ctx.rotate(angle);
setRandomColor();
ctx.beginPath();
ctx.moveTo(0, 0);
let x1 = Math.cos(Math.PI/3+a) * this.R;
let y1 = Math.sin(Math.PI/3+a) * this.R;
ctx.lineTo(x1, y1);
let x2 = Math.cos(a) * this.R;
let y2 = Math.sin(a) * this.R;
ctx.lineTo(x2, y2);
ctx.lineTo(0, 0);
ctx.fill();
ctx.stroke();
setRandomColor();
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(x2, y2);
let x3 = Math.cos(-Math.PI/3+a) * this.R;
let y3 = Math.sin(-Math.PI/3+a) * this.R;
ctx.lineTo(x3, y3);
ctx.lineTo(0, 0);
ctx.fill();
ctx.stroke();
}
ctx.restore();
}
}
function setup() {
setupColors();
canvas = document.querySelector("#canvas");
ctx = canvas.getContext("2d");
window.addEventListener("resize", resize);
canvas.addEventListener("click", draw);
resize();
}
function setupColors() {
//https://coolors.co
colors = [
[
"#ffbe0b",
"#fb5607",
"#ff006e",
"#8338ec",
"#3a86ff"
],
[
"#432371",
"#714674",
"#9f6976",
"#cc8b79",
"#faae7b"
],
[
"#e0fbfc",
"#c2dfe3",
"#9db4c0",
"#5c6b73",
"#253237"
],
[
"#f4f1de",
"#e07a5f",
"#3d405b",
"#81b29a",
"#f2cc8f"
],
];
}
function setRandomColor() {
let len = colors[colorSchemeIndex].length;
let randomIndex = Math.floor(Math.random() * len);
let color = colors[colorSchemeIndex][randomIndex];
ctx.strokeStyle = color;
ctx.fillStyle = color;
}
function resize() {
w = canvas.width = window.innerWidth;
h = canvas.height = window.innerHeight;
draw();
}
function setupHexagons() {
hexagons = [];
let r = Math.random() * 80 + 15;
let R = r / Math.cos(Math.PI / 6);
let t = r * 2 / Math.sqrt(3);
let rows = w / (r * 2) + 1;
let cols = h / R;
for(let x = 0; x < rows; x++) {
for(let y = 0; y < cols; y++) {
let xOffset = y % 2 === 0 ? r : 0;
let xPixel = r * x * 2 + xOffset;
let yPixel = (t/2 + R) * y;
let hexagon = new Hexagon(xPixel, yPixel, R);
hexagons.push(hexagon);
}
}
}
function draw() {
ctx.clearRect(0, 0, w, h);
let nrOfColorSchemes = colors.length;
colorSchemeIndex = Math.floor(Math.random() * nrOfColorSchemes);
setupHexagons();
hexagons.forEach(h => {
h.draw();
});
}
setup();
View Compiled
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.