xxxxxxxxxx
71
// see https://discourse.processing.org/t/brightness-with-original-background-image/15792/2
// based on mouse_color by kll
let infile = 'assets/galaxy.jpg';
let showorg = false;
let rad = 100;
function preload() {
img = loadImage(infile);
}
function setup() {
createCanvas(800, 450);
pixelDensity(1);
img.loadPixels();
loadPixels();
}
function draw() {
// optionally show original image
if (showorg){
image(img, 0, 0);
return;
}
loadPixels();
// set black background
pixels.fill(0);
for(let i=0; i<pixels.length/4; i++){
pixels[i*4+3] = 255;
}
// compute spotlight for area only
let minx = max(mouseX-rad,0);
let miny = max(mouseY-rad,0);
let maxx = min(mouseX+rad,width);
let maxy = min(mouseY+rad,height);
for (let x = minx; x < maxx; x++) {
for (let y = miny; y < maxy; y++) {
let loc = (x + y * img.width) * 4; //___ Calculate the 1D location from a 2D grid
let r, g, b; //_________________________ Get the R,G,B values from image
r = img.pixels[loc];
g = img.pixels[loc + 1];
b = img.pixels[loc + 2];
// Calculate an amount to change brightness based on proximity to the mouse
let maxdist = 50;
let d = dist(x, y, mouseX, mouseY);
let adjustbrightness = (255 * (maxdist - d)) / maxdist;
r += adjustbrightness;
g += adjustbrightness;
b += adjustbrightness;
// Constrain RGB to make sure they are within 0-255 color range
r = constrain(r, 0, 255);
g = constrain(g, 0, 255);
b = constrain(b, 0, 255);
// Make a new color and set pixel in the window
let pixloc = (y * width + x) * 4;
pixels[pixloc] = r;
pixels[pixloc + 1] = g;
pixels[pixloc + 2] = b;
pixels[pixloc + 3] = 255;
}
}
updatePixels();
}
function keyPressed() {
if (key == 'o') showorg = !showorg;
}