xxxxxxxxxx
95
let cols, rows;
let size = 1;
let m = 0;
let n = 0;
let threshold = 0.18
let gridSize = 4; // 4x4 grid
function setup() {
createCanvas(400, 800);
cols = width / (size * gridSize);
rows = height / (size * gridSize);
}
function draw() {
background(220);
noStroke();
// Draw each cell in the 4x4 grid
for (let gridX = 0; gridX < gridSize; gridX++) {
for (let gridY = 0; gridY < gridSize; gridY++) {
// Determine if we should mirror in x and/or y direction
let mirrorX = gridX % 2 === 1;
let mirrorY = gridY % 2 === 1;
// Draw the Chladni pattern for this grid cell
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
// Calculate the position within the individual pattern
let x = map(i, 0, cols, 0, 1);
let y = map(j, 0, rows, 0, 1);
// Apply mirroring if needed
if (mirrorX) x = 1 - x;
if (mirrorY) y = 1 - y;
// Calculate the Chladni value and determine fill color
let val = chladni(x, y);
if (abs(val) < threshold) {
fill("purple");
} else {
fill("yellow");
}
// Calculate the position on the canvas
let posX = gridX * cols * size + i * size;
let posY = gridY * rows * size + j * size;
rect(posX, posY, size, size);
}
}
}
}
// Draw grid lines
stroke("red");
strokeWeight(2);
for (let i = 1; i < gridSize; i++) {
noStroke();
line(i * width/gridSize, 0, i * width/gridSize, height);
line(0, i * height/gridSize, width, i * height/gridSize);
}
noLoop();
}
function chladni(x, y) {
let L = 1;
return cos(n * PI * x / L) * cos(m * PI * y / L) -
cos(m * PI * x / L) * cos(n * PI * y / L);
}
// keyboard controls to change parameters
function keyPressed() {
if (key === 'n') {
n = (n + 1) % 10;
console.log("n= "+ n)
redraw();
} else if (key === 'm') {
m = (m + 1) % 10;
console.log("m= " +m)
redraw();
} else if (key === 't') {
threshold += 0.01;
if (threshold > 0.2) threshold = 0.01;
redraw();
} else if (key === 'p') {
saveCanvas();
}
}