Basic Examples

These examples demonstrate fundamental concepts in P5 Svelte. Each example showcases different features and can serve as a starting point for your own sketches.

Drawing Example

Basic Drawing

Click and drag to draw on the canvas:

FPS: 60
View Code
const sketch: Sketch = {
  setup: (p5) => {
    p5.background(220);
  },
  draw: (p5) => {
    p5.stroke(0);
    if (p5.mouseIsPressed) {
      p5.line(p5.mouseX, p5.mouseY,
        p5.pmouseX, p5.pmouseY);
    }
  }
};

Shapes and Colors

Basic Shapes with Color Animation

Demonstrates different shapes with animated color transitions:

FPS: 60
View Code
const sketch: Sketch = {
  setup: (p5) => {
    p5._hue = 0;
  },
  draw: (p5) => {
    p5.background(220);
    p5.colorMode(p5.HSB, 360, 100, 100);

    p5._hue = (p5._hue + 1) % 360;

    p5.fill(p5._hue, 80, 90);
    p5.noStroke();
    p5.rect(50, 50, 100, 100);

    p5.fill((p5._hue + 120) % 360, 80, 90);
    p5.ellipse(250, 100, 100, 100);

    p5.fill((p5._hue + 240) % 360, 80, 90);
    p5.triangle(400, 50, 350, 150, 450, 150);
  }
};

Basic Animation

Rotating Square

Demonstrates basic animation and transformation:

FPS: 60
View Code
const sketch: Sketch = {
  setup: (p5) => {
    p5._angle = 0;
  },
  draw: (p5) => {
    p5.background(220);
    p5.translate(p5.width/2, p5.height/2);
    p5.rotate(p5._angle);

    p5.fill(255, 0, 0);
    p5.rectMode(p5.CENTER);
    p5.rect(0, 0, 100, 100);

    p5._angle += 0.02;
  }
};

Key Concepts Demonstrated

Setup and Draw

Understanding the basic lifecycle of a P5.js sketch

Event Handling

Responding to mouse and keyboard input

State Management

Managing and updating sketch state

Next Steps

Ready for more advanced examples? Check out: