1 min read

p5.js animation example

<!DOCTYPE html>
<html lang="fr">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="author" content="Rong Zhou">
    <title>Animation Copier Progression</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.min.js"></script>
    <script defer>
      // p5.js sketch: 720x1280 canvas, cycles background images and titles every 1s

let images = [];
let titles = ["1000 CE", "1980 CE", "2000 CE", "2020 CE"];

function preload() {
  images[0] = loadImage("https://upload.wikimedia.org/wikipedia/commons/c/c9/The_Scribe_at_Work.jpg");
  images[1] = loadImage("https://upload.wikimedia.org/wikipedia/commons/thumb/f/f5/Sharp_MX-7500_photocopier.jpg/1024px-Sharp_MX-7500_photocopier.jpg");
  images[2] = loadImage("https://upload.wikimedia.org/wikipedia/commons/7/7b/Smargo_SmartReader_Plus_02_Groessenvergleich.jpg");
  images[3] = loadImage("https://upload.wikimedia.org/wikipedia/commons/b/bb/Employee_Training_-_Communication_Skills_Illustration.jpg");
}

function setup() {
  const canvas = createCanvas(windowWidth, windowHeight); // Set canvas size to 100vw and 100vh
  canvas.parent("p5-animation"); // Attach the canvas to the specific div
  textAlign(CENTER, CENTER);
  textSize(72);
}

function windowResized() {
  resizeCanvas(windowWidth, windowHeight); // Adjust canvas size on window resize
}

function draw() {
  background(0);

  // Change every 1000 ms
  const idx = Math.floor((millis() / 1000) % images.length);

  // Draw background image covering the screen
  drawCover(images[idx]);

  // Overlay for readability
  noStroke();
  fill(0, 0, 0, 120);
  rect(0, height * 0.75 - 100, width, 200);

  // Draw title text in white
  fill(255);
  text(titles[idx], width / 2, height * 0.75);
}

// Draw an image to cover the entire canvas while preserving aspect ratio
function drawCover(img) {
  if (!img || !img.width || !img.height) return;

  const scale = Math.max(width / img.width, height / img.height);
  const w = img.width * scale;
  const h = img.height * scale;
  const x = (width - w) / 2;
  const y = (height - h) / 2;

  image(img, x, y, w, h);
}

    </script>
  </head>
  <body>
    <div id="p5-animation" style="width: 100vw; margin: auto;"></div>
  </body>
</html>