Week 10: Media, Drawing & Animation

To Do This Week

Explore the front-end modules this week and next. By the end of Week 11 you will have tried five techniques you can combine in your two Front-End Module Projects.

Keep a running list of combination ideas as you go. Each sandbox ends with one question: What would I combine this with?


Front-End Module Projects (10% + 10%)

Complete two independent projects after exploring the course’s front-end modules. Each project must combine at least two of the following:

The projects should demonstrate creative intent rather than merely showing that a feature works. These are small ways to play with techniques that can lead toward your final project.

Minimum Requirements for Each Project

Using AI

You may use AI to research and test out an idea. If you use AI to build logic steps and syntax, use JS Mentor. Document what AI contributed and how you evaluated, changed, and extended the generated material. Include chat URLs in your script comments.


Monday: Audio/Video, SVG & Canvas Drawing

There are three ways to put expressive media on a page with JavaScript:


HTML5 Audio & Video

Sound and moving image are often the fastest way to give a project mood. They also combine easily with everything else this week: a click on an SVG shape plays a sound, a video drives a canvas, a game event triggers a sound effect.

Audio with JavaScript

const chime = new Audio('chime.mp3');  // load a sound file

chime.play();           // play it
chime.pause();          // pause it
chime.currentTime = 0;  // rewind to the start (so it can retrigger)
chime.volume = 0.5;     // 0 to 1
chime.loop = true;      // repeat

Video with JavaScript

<video id="clip" src="clip.mp4" muted playsinline></video>

const clip = document.getElementById('clip');

clip.play();
clip.pause();
clip.playbackRate = 0.5;   // slow motion (2 = double speed)
clip.currentTime = 10;     // jump to 10 seconds

// Run code as the video plays
clip.addEventListener('timeupdate', () => {
  console.log(clip.currentTime + ' / ' + clip.duration);
});

// Run code when it finishes
clip.addEventListener('ended', () => {
  console.log('done');
});

SVG (Scalable Vector Graphics) and JS

From Illustrator to JavaScript

  1. Name your layers clearly in Illustrator before exporting. Layer names become ids.
  2. Export as SVG and open the SVG code.
  3. Paste the <svg> block into your HTML.
  4. Check that the ids match what you expect, then select them with getElementById().

New Syntax

const face = document.getElementById('face');

face.setAttribute('fill', 'lightblue');               // change color
face.setAttribute('r', '150');                        // change radius
face.setAttribute('transform', 'rotate(15 300 300)'); // rotate around center
face.removeAttribute('transform');                    // undo

Demos


Canvas: JS Drawing

Setting Up

<canvas id="myCanvas" width="600" height="600"></canvas>

const c = document.getElementById('myCanvas');
const ctx = c.getContext('2d');   // the drawing toolkit

Important: CSS width and height only change the display size. The drawing size comes from the width and height attributes on the <canvas> tag. If CSS stretches a 600 × 600 canvas to 800px, your drawing commands still use 600 × 600 coordinates.

Basic Drawing Methods

Drawing Circles and Arcs

Mouse Position on the Canvas

c.addEventListener('mousemove', (e) => {
  const rect = c.getBoundingClientRect(); // canvas position on the page
  const mx = e.clientX - rect.left;       // mouse x inside the canvas
  const my = e.clientY - rect.top;        // mouse y inside the canvas
  drawFace(mx, my);                       // redraw with new values
});

Demos

Compare: open the SVG Smiley and the Canvas Smiley side by side. Both make the pupils follow the mouse with the same constrainPupil() math. SVG moves two circles with setAttribute(). Canvas clears and repaints the whole face on every mouse move.


Monday In-Class Sandbox

Make your own face, figure, or object that responds to the user. Choose SVG or Canvas.

  1. Start from one of the smiley demos. Use the coordinate display to find positions.
  2. Change the drawing into something of your own: a creature, a mask, a machine, an object with a personality.
  3. Add one interaction: hover, click, mouse tracking, or a slider.
  4. Add a sound with new Audio() that plays on that interaction.

What would I combine this with? Write one sentence in a comment at the top of your script.


Wednesday: Canvas Animation & p5.js

Canvas Animation

Canvas animation is drawing frame by frame. Each frame you clear the canvas, update values (position, size, color), and redraw. Repeat that many times per second and you get motion.

The Animation Loop

let x = 0;        // position
let speed = 2;    // velocity: how far it moves each frame

function animate() {
  ctx.clearRect(0, 0, c.width, c.height);  // 1. clear

  x += speed;                               // 2. update
  if (x > c.width || x < 0) speed *= -1;   //    bounce at the edges

  ctx.beginPath();                          // 3. draw
  ctx.arc(x, 300, 20, 0, 2 * Math.PI);
  ctx.fill();

  requestAnimationFrame(animate);           // 4. repeat
}

animate();

Demos


Generative Art

Generative visual art is digital art made using computer algorithms. Artists use programming tools like Processing or its JavaScript version p5.js to set rules. The computer then creates art by following these rules, leading to unique and sometimes changing images or animations. The artist decides the starting point, but the computer’s actions create the final piece.

GENERATIVE ART: Art created using autonomous processes

AUTONOMOUS PROCESS: A process not under direct human control

— Amy Goodchild

random() vs. noise()

random() generates pseudorandom numbers: a value between 0 and 1, a number within a range, or a random element from an array. Each value jumps independently of the last, which is useful for unpredictability and variation.

Example of p5.js random() output

noise() generates Perlin noise: smooth, gradient-based randomness. Values change gradually, which makes them ideal for organic patterns, textures, terrain, clouds, and natural-looking motion.

Example of p5.js noise() output

Images from Amy Goodchild’s What is Generative Art. Try it yourself: random() vs noise().

Vera Molnár

Vera Molnár (1924–2023) was a Hungarian-French artist recognized as one of the earliest pioneers of generative and computer-based art. In the late 1960s, she began systematically using computers, an uncommon practice at the time, to explore geometric forms and algorithmic variations. Her rule-based series of drawings reveal slight, methodical permutations in composition, showing how simple computational rules can generate nuanced aesthetic complexity.

Vera Molnar example

John Conway

John Conway’s Game of Life (p5.js simulation) — complex, lifelike patterns from a few simple rules.


p5.js

p5.js is a JavaScript library that makes Canvas drawing and animation simpler. It runs the animation loop for you and adds tools for randomness, noise, color, and transformation.

New Syntax

function setup() {          // runs once at the start
  createCanvas(600, 600);
}

function draw() {           // runs every frame (about 60 per second)
  background(20, 20);       // low alpha leaves trails
  let x = noise(frameCount * 0.01) * width;  // smooth drifting value
  let size = random(5, 30);                  // jittery value
  fill(255);
  circle(x, height / 2, size);
}

p5.js Starter Sketches

  1. p5js shapes
  2. p5js square grid
  3. p5js animating with frameCount
  4. p5js drawing
  5. p5js velocity
  6. p5js bouncing balls
  7. p5js HTML starter template — for moving a sketch from the editor to your own page

p5.js Demos


Generative Techniques to Explore

Use these sample prompts with AI to see each technique quickly. Then change the rules and values yourself.

Flow Fields

A grid where each cell holds a vector that steers particles moving across it. With noise generating the vectors, the paths look like wind, water, or magnetic currents. Tyler Hobbs on flow fields.

Prompt: “Write a p5.js sketch that creates a flow field using Perlin noise, where 100 particles move according to the flow vectors. The sketch should visualize the paths in real time.”

Perlin Noise Fields

Sampling noise across a grid and over time produces textures like clouds, terrain, or smoke.

Prompt: “Generate p5.js code that draws a 2D Perlin noise field in grayscale, continuously updating over time to look like clouds.”

Particle Systems

Many small particles follow simple rules, often released from an emitter. Add gravity, drag, and variation to simulate fire, smoke, sparks, or dense evolving compositions.

Prompt: “Create a p5.js sketch of a particle system where new particles are emitted from the bottom center of the screen and rise upwards, fading out over time.”

Boids / Flocking

Craig Reynolds’s model of bird flocking: each boid follows rules of separation, alignment, and cohesion, and group movement emerges.

Prompt: “Write a p5.js sketch implementing boids flocking with 50 boids. They should avoid overlapping, try to move with neighbors, and stay within the canvas area.”

Fractals & Recursion

Recursive functions draw self-similar patterns across scales: trees, L-systems, the Mandelbrot set.

Prompt: “Generate a p5.js fractal tree sketch that uses recursion to draw multiple branches from each node, with sliders to control branch angle and depth.”

Cellular Automata

Each cell in a grid changes state based on its neighbors. Conway’s Game of Life is the classic example.

Prompt: “Create a p5.js version of Conway’s Game of Life with a grid of 50×50 cells, using random initialization, and animate each generation.”

Data Visualization & Sonification

Data encoded as color, position, shape, or sound. Next week’s fetch() module brings in live data you could visualize this way.

Prompt: “Create a p5.js data visualization of US debt over 50 years.”


Wednesday In-Class Sandbox

Make a small animated piece that expresses a mood. Choose plain Canvas or p5.js.

  1. Start from a demo: the snowfall or rain demo, a p5.js starter sketch, or a sample prompt above.
  2. Change at least one rule, not just a value: how things move, how they are born and die, how they respond to the mouse.
  3. Try swapping random() for noise() (or the reverse) and notice how the feeling changes.
  4. Optional: add a sound or a looping audio track that fits the mood.

Use AI freely to research and test ideas today. If you take an idea further toward a project, use JS Mentor to work out the logic steps and syntax.

What would I combine this with? Add one sentence to your list.


p5.js Resources