Code

p5.js

Sketch Basics

Beginner The setup() / draw() loop — primitive shapes (rect, ellipse, beginShape), fill, stroke, rotate, translate, and push() / pop() matrix isolation. p5.js Docs

const sketch = (p) => {
  p.setup = () => {
    p.createCanvas(500, 300).parent(container);
    p.frameRate(60);
    p.angleMode(p.DEGREES);
    p.colorMode(p.HSB, 360, 100, 100, 100);
  };

  p.draw = () => {
    p.background(220, 20, 12);

    // Rotating rectangle
    p.push();
    p.translate(p.width * 0.2, p.height / 2);
    p.rotate(angle);
    p.fill(200, 80, 90);
    p.noStroke();
    p.rectMode(p.CENTER);
    p.rect(0, 0, 60, 60, 8);
    p.pop();

    // Pulsing ellipse
    const r = 30 + Math.sin(p.radians(angle * 2)) * 15;
    p.push();
    p.translate(p.width * 0.5, p.height / 2);
    p.fill(40, 90, 95);
    p.ellipse(0, 0, r * 2, r * 2);
    p.pop();

    // Polygon via beginShape / vertex
    p.push();
    p.translate(p.width * 0.8, p.height / 2);
    p.rotate(-angle * 0.7);
    p.fill(280, 70, 90);
    p.beginShape();
    for (let i = 0; i < 3; i++) {
      const a = (360 / 3) * i - 90;
      p.vertex(cos(a) * 35, sin(a) * 35);
    }
    p.endShape(p.CLOSE);
    p.pop();

    angle += 1.2;
  };
};

new p5(sketch);