p5(sketch => {
sketch.setup = function() {
sketch.createCanvas(width, height);
sketch.colorMode(sketch.HSB, 360, 100, 100, 100);
sketch.noStroke();
sketch.rect(0, 0, width, height);
};
function gradient(x, y, w, h, c1, c2) {
var ctx = sketch.drawingContext;
var grd = ctx.createLinearGradient(x, y, x, y + h);
grd.addColorStop(0, c1.toString());
grd.addColorStop(1, c2.toString());
ctx.fillStyle = grd;
ctx.fillRect(x, y, w, h);
}
sketch.draw = function() {
sketch.noLoop();
sketch.background(0);
var counter = 0;
const maxHeight = 150;
const minHeight = 5;
const maxWidth = width / 4;
const minWidth = 1;
const rowsY = randomIntFromInterval(minHeight, maxHeight);
const rowsX = randomIntFromInterval(1, 15);
let randomRectangles = [];
for (let gridY = 0; gridY < rowsY; gridY++) {
let gridYHeight = randomIntFromInterval(minHeight, maxHeight);
randomRectangles.push({
row: gridY,
height: gridYHeight,
grid_rect : gridYHeight,
prev_grid_rect : 0,
width: 0
})
let previousHeight = 0;
if (gridY > 0) {
previousHeight = d3.sum(randomRectangles.filter((d, i) => i < gridY), d => d.height);
randomRectangles[gridY].prev_grid_rect = randomRectangles[gridY - 1].prev_grid_rect;
} else if (gridY === rowsY - 1) {
gridYHeight = height - previousHeight + randomRectangles[gridY - 1].prev_grid_rect / 2;
randomRectangles[gridY].height = gridYHeight;
}
for (let gridX = 0; gridX < rowsX; gridX++) {
let gridXWidth = randomIntFromInterval(minWidth, maxWidth);
const posY = previousHeight - randomRectangles[gridY].prev_grid_rect / 2;
let posX = randomRectangles[gridY].width;
if (gridX === rowsX - 1) {
gridXWidth = width - randomRectangles[gridY].width;
}
randomRectangles[gridY].width = randomRectangles[gridY].width + gridXWidth;
if (posX > width) {
posX = 0;
gridXWidth = 0;
}
const index = counter % colour_count;
const colour = sketch.color(hueValues[index], saturationValues[index], brightnessValues[index]);
var colour_start = sketch.color(0, 0, 0, 25);
gradient(posX, posY, gridXWidth, gridYHeight, colour_start, colour);
counter++;
}
}
}
})