Media: Pixels

Work with pixelDensity(1), get(), and pixels[] sampling.

Example 1: get() Sampler

Code

let img;

function preload() {
  img = loadImage('../assets/images/map.jpg');
}

function setup() {
  createCanvas(400, 400);
  pixelDensity(1);
}

function draw() {
  image(img, 0, 0, width, height);
  const c = get(mouseX, mouseY);
  fill(c);
  noStroke();
  rect(12, 12, 80, 80, 8);

  stroke(255, 45, 140);
  noFill();
  circle(mouseX, mouseY, 18);
}

Try this: Sample a 10x10 area and average color values.

Open sketch in new tab

Example 2: pixels[] Read

Code

let img;

function preload() {
  img = loadImage('../assets/images/map.jpg');
}

function setup() {
  createCanvas(400, 400);
  pixelDensity(1);
}

function draw() {
  image(img, 0, 0, width, height);
  loadPixels();
  const x = constrain(mouseX, 0, width - 1);
  const y = constrain(mouseY, 0, height - 1);
  const idx = (y * width + x) * 4;
  const r = pixels[idx];
  const g = pixels[idx + 1];
  const b = pixels[idx + 2];

  fill(255);
  rect(10, 10, 150, 40, 6);
  fill(20);
  text('r ' + r + ' g ' + g + ' b ' + b, 18, 35);
}

Try this: Use sampled brightness to control particle speed.

Open sketch in new tab

Resources