xxxxxxxxxx
68
let capture;
let cellSize = 12; // Width and height of each cell in the grid, now adjustable
// ASCII characters arranged by density
const asciiChars = ' .:-=+*#%@';
function setup() {
createCanvas(640, 480);
// Start video capture
capture = createCapture(VIDEO);
capture.size(640, 480);
capture.hide(); // Hide the video element
textAlign(CENTER, CENTER);
textSize(15);
textFont('monospace');
}
function draw() {
background(0);
// Load pixels from the video
capture.loadPixels();
// Only proceed if we have pixels to work with
if (capture.pixels.length > 0) {
// Calculate number of cells based on cell size
const cols = width / cellSize;
const rows = height / cellSize;
// Loop through the grid
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
const x = i * cellSize;
const y = j * cellSize;
// Get the pixel index
const pixelIndex = (y * width + x) * 4;
// Get RGB values
const r = capture.pixels[pixelIndex];
const g = capture.pixels[pixelIndex + 1];
const b = capture.pixels[pixelIndex + 2];
// Calculate brightness (0-255)
const brightness = (r + g + b) / 3;
// Map brightness to ASCII character index
const charIndex = floor(map(brightness, 0, 255, 0, asciiChars.length));
const c = asciiChars[charIndex];
fill(255);
// Draw the ASCII character
text(c, x + cellSize/2, y + cellSize/2);
}
}
}
}
// Handle arrow key presses
function keyPressed() {
if (keyCode === UP_ARROW) {
cellSize = constrain(cellSize + 1, 4, 24); // Increase grid size
textSize(cellSize * 1.25); // Adjust text size proportionally
} else if (keyCode === DOWN_ARROW) {
cellSize = constrain(cellSize - 1, 4, 24); // Decrease grid size
textSize(cellSize * 1.25); // Adjust text size proportionally
}
}