xxxxxxxxxx
63
// Convert an image to a black-and-white pixelated grid image.
//
// Visualization:
// https://editor.p5js.org/kyeah/sketches/EHtyYEEyz
let img;
let pixelSize = 5;
function preload() {
img = loadImage('amp.jpg')
}
function setup() {
cnv = createCanvas(windowWidth, windowHeight);
cnv.mousePressed(change);
colorMode(HSB, 255)
// 1. Resize the image to fit the canvas.
if (img.width < img.height) {
// If it's longer horizontally, fit the canvas width
// and resize the height proportionally.
img.resize(width, 0)
} else {
// If it's longer vertically, fit the canvas height
// and resize the width proportionally.
img.resize(0, height)
}
// Only run the draw function once, otherwise
// the program might work too hard redrawing things!
noLoop()
}
function draw() {
background('#f4dbd2');
// 2. For each point in the grid...
for (let x = 0; x < img.width; x += pixelSize) {
for (let y = 0; y < img.height; y += pixelSize) {
// Get the brightness value for the image at (x, y)
let brightnessVal = brightness(img.get(x, y))
// If it's dark, fill our grid square with black.
// Otherwise, don't fill it.
if (brightnessVal < 127) {
fill('#000')
} else {
noFill()
}
// Draw our grid square!
textSize(pixelSize);
text("&", x, y)
}
}
}
function change() {
pixelSize = mouseX/20;
draw();
}