Creative Coding · Session c04

Mouse + Touch

Make art with your finger — a rainbow painting canvas.

Today you're building a real finger-painting tool. On the iPad it works with touch; on a laptop it follows the mouse. The key trick is pmouseX / pmouseY — the previous mouse position. Drawing a line from the previous point to the current point creates a smooth stroke instead of disconnected dots.

Live sketch — Finger Painter

Press and drag (or touch and drag on iPad) to draw. The colour slowly cycles through the rainbow as you paint.

let hue = 0; // starts at red function setup() { createCanvas(420, 300); background(245); // light grey starting canvas colorMode(HSB, 360, 100, 100); } function draw() { if (mouseIsPressed) { hue = (hue + 1) % 360; // advance hue by 1° each frame stroke(hue, 90, 80); strokeWeight(10); // draw from PREVIOUS position to CURRENT — smooth line! line(pmouseX, pmouseY, mouseX, mouseY); } } // touchMoved prevents scrolling the page while painting function touchMoved() { return false; }
Why pmouseX? Each frame, the mouse may have moved 10 or 20 pixels since last frame. If you drew a circle at just the current position, you'd get a dotted line. By drawing a line from where it was to where it is now, you fill in the gap and get a smooth stroke. This is how every drawing app works!
Challenges
  1. Change strokeWeight(10) to make thicker or thinner strokes. Try basing it on speed: how far did the mouse move this frame? dist(pmouseX, pmouseY, mouseX, mouseY) gives you that distance.
  2. Add a keyboard shortcut: pressing 'c' clears the canvas. In p5.js, add a function keyPressed() and check if (key === 'c') background(245);
  3. Mirror mode: draw each stroke twice — once normally, and once mirrored at width - mouseX, mouseY. You'll get a symmetric butterfly painting!
  4. Change saturation based on mouseY: near the top = vivid, near the bottom = pastel.
  5. Open challenge: Make a "spray can" effect — instead of one line, draw 10–20 small circles in random positions near the mouse, each frame. Use random(-15, 15) to scatter them.
Next session → c05: Loops + Patterns You'll use nested for loops to fill the whole canvas with a grid of coloured tiles — and animate them so the pattern breathes and shifts like a living tapestry.
← All lessons
Focus 25:00

Ask your tutor