Interaction: UI Controls

Control visuals with p5 DOM sliders and input values.

Example 1: Size Slider

Code

let slider;

function setup() {
  createCanvas(400, 400);
  slider = createSlider(20, 220, 80, 1);
  slider.position(16, 16);
  slider.style('width', '180px');
}

function draw() {
  background(250);
  const s = slider.value();
  fill(255, 48, 145);
  noStroke();
  circle(width / 2, height / 2, s);

  fill(20);
  text('Size: ' + s, 16, 54);
}

Try this: Use slider input to control strokeWeight as well.

Open sketch in new tab

Example 2: RGB Sliders

Code

let r, g, b;

function setup() {
  createCanvas(400, 400);
  r = createSlider(0, 255, 255, 1); r.position(16, 16);
  g = createSlider(0, 255, 60, 1);  g.position(16, 44);
  b = createSlider(0, 255, 140, 1); b.position(16, 72);
  r.style('width', '160px');
  g.style('width', '160px');
  b.style('width', '160px');
}

function draw() {
  background(245);
  fill(r.value(), g.value(), b.value());
  rect(120, 140, 180, 180, 16);
  fill(20);
  text('R ' + r.value() + ' G ' + g.value() + ' B ' + b.value(), 120, 340);
}

Try this: Add a fourth slider for alpha and draw overlapping shapes.

Open sketch in new tab

Resources