xxxxxxxxxx
42
function setup() {
let img = createImage(100, 100); // same as new p5.Image(100, 100);
img.loadPixels();
createCanvas(100, 100);
background(0);
// helper for writing color to array
function writeColor(image, x, y, r, g, b, a) {
let index = (x + y * width) * 4;
image.pixels[index] = r;
image.pixels[index + 1] = g;
image.pixels[index + 2] = b;
image.pixels[index + 3] = a;
}
let x, y;
// fill with random colors
for (y = 0; y < img.height; y++) {
for (x = 0; x < img.width; x++) {
let r = random(255);
let g = random(255);
let b = random(255);
let a = 255;
writeColor(img, x, y, r, g, b, a);
}
}
// draw a red line
y = 0;
for (x = 0; x < img.width; x++) {
writeColor(img, x, y, 255, 0, 0, 255);
}
// draw a green line
y = img.height - 1;
for (x = 0; x < img.width; x++) {
writeColor(img, x, y, 0, 255, 0, 255);
}
img.updatePixels();
image(img, 0, 0);
}