xxxxxxxxxx
122
// https://www.youtube.com/watch?v=7DSrPckZctw
// a p5js variation of the course:
// Creating an interactive Grid System with Processing
// by Tim Rodenbröker
let gridSize = 3;
let maxVariations = 5;
let state = [];
let img1, img2, img3;
let tileW;
let tileH;
let imageNumber = 0;
function preload() {
img1 = loadImage("1.jpg");
img1.resize(width, height);
img2 = loadImage("2-1.jpg");
img2.resize(width, height);
img3 = loadImage("3.jpg");
img3.resize(width, height);
}
function setup() {
createCanvas(900, 900);
tileW = width / gridSize;
tileH = height / gridSize;
fill2DArray(gridSize, state, maxVariations);
ellipseMode(CORNER);
}
function draw() {
background(0);
image(img1, 0, 0);
fill(255, 200, 10);
noStroke();
for (let x = 0; x < gridSize; x++) {
for (let y = 0; y < gridSize; y++) {
// state decisions
if (state[x][y] === 0) {
push();
translate(x * tileW, y * tileH);
ellipse(0, 0, tileW, tileH);
pop();
}
if (state[x][y] === 1) {
push();
translate(x * tileW, y * tileH);
rect(0, 0, tileW, tileH);
pop();
}
if (state[x][y] === 2) {
push();
translate(x * tileW, y * tileH);
triangle(0, 0, tileW, tileH, 0, tileH);
pop();
}
if (state[x][y] === 3) {
// nothing - just show the background
}
if (state[x][y] === 4) {
let sx = floor(x * tileW);
let sy = floor(y * tileH);
let sw = tileW;
let sh = tileH;
let dx = sx;
let dy = sy;
let dw = tileW;
let dh = tileH;
copy(img3, sx, sy, sw, sh, dx, dy, dw, dh);
}
if (state[x][y] === 5) {
let sx = floor(x * tileW);
let sy = floor(y * tileH);
let sw = tileW;
let sh = tileH;
let dx = sx;
let dy = sy;
let dw = tileW;
let dh = tileH;
copy(img2, sx, sy, sw, sh, dx, dy, dw, dh);
}
}
}
}
function mouseReleased() {
let x = floor(mouseX / tileW);
let y = floor(mouseY / tileH);
countUp(state, x, y, maxVariations);
// uncomment to save the canvas
// saveCanvas("grid"+imageNumber, "jpg");
imageNumber++;
}
// count up
function countUp(array, x, y, maxVariations) {
if (array[x][y] < maxVariations) {
array[x][y]++;
} else {
array[x][y] = 0;
}
}
// makes a random 2D array
function fill2DArray(size, array, maxVariations) {
for (let x = 0; x < gridSize; x++) {
array[x] = [];
for (let y = 0; y < gridSize; y++) {
array[x][y] = floor(random(0, maxVariations + 1));
}
}
}