Brightness
By Dan Shiffman. This program adjusts the brightness of a part of the image by calculating the distance of each pixel to the mouse.
To run this example locally, you will need at least an image file and a running local server.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
let img;
function preload() {
img = loadImage('assets/moonwalk.jpg');
}
function setup() {
createCanvas(720, 200);
pixelDensity(1);
img.loadPixels();
loadPixels();
}
function draw() {
for (let x = 0; x < img.width; x++) {
for (let y = 0; y < img.height; y++) {
// Calculate the 1D location from a 2D grid
let loc = (x + y * img.width) * 4;
// Get the R,G,B values from image
let r, g, b;
r = img.pixels[loc];
// 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;
// Constrain RGB to make sure they are within 0-255 color range
r = constrain(r, 0, 255);
// Make a new color and set pixel in the window
//color c = color(r, g, b);
let pixloc = (y * width + x) * 4;
pixels[pixloc] = r;
pixels[pixloc + 1] = r;
pixels[pixloc + 2] = r;
pixels[pixloc + 3] = 255;
}
}
updatePixels();
}