P5.js Interactive Visualizations
P5.js is a JavaScript library for creative coding and interactive visualizations. Perfect for creating custom animations, data visualizations, and interactive diagrams that go beyond static charts.
Use Case
Use P5.js when you need to:
- Create custom interactive visualizations
- Animate data or concepts
- Build interactive demos
- Visualize algorithms in action
- Create generative art or patterns
Code
1```p5js
2sketch.setup = function() {
3 sketch.createCanvas(400, 300);
4};
5
6sketch.draw = function() {
7 sketch.background(220);
8 sketch.ellipse(sketch.mouseX, sketch.mouseY, 50, 50);
9};
10```
Explanation
setup()- Runs once at start, initialize canvasdraw()- Runs continuously (60fps by default)createCanvas(w, h)- Create drawing canvasbackground(color)- Clear canvas with colormouseX, mouseY- Current mouse position- Drawing functions:
ellipse(),rect(),line(), etc.
Examples
Example 1: Simple Animation
1```p5js
2let x = 0;
3
4sketch.setup = function() {
5 sketch.createCanvas(400, 200);
6};
7
8sketch.draw = function() {
9 sketch.background(240);
10
11 // Moving circle
12 sketch.fill(100, 150, 250);
13 sketch.ellipse(x, 100, 40, 40);
14
15 x = x + 2;
16 if (x > sketch.width) {
17 x = 0;
18 }
19};
20```
Result:
Example 2: Data Visualization
1```p5js
2let data = [45, 67, 89, 34, 78, 56, 90, 23];
3
4sketch.setup = function() {
5 sketch.createCanvas(400, 300);
6 sketch.noLoop(); // Draw once
7};
8
9sketch.draw = function() {
10 sketch.background(255);
11
12 let barWidth = sketch.width / data.length;
13
14 for (let i = 0; i < data.length; i++) {
15 let barHeight = sketch.map(data[i], 0, 100, 0, sketch.height - 40);
16
17 sketch.fill(100, 150, 250);
18 sketch.rect(i * barWidth, sketch.height - barHeight, barWidth - 2, barHeight);
19
20 // Labels
21 sketch.fill(0);
22 sketch.textAlign(sketch.CENTER);
23 sketch.text(data[i], i * barWidth + barWidth/2, sketch.height - barHeight - 5);
24 }
25};
26```
Result:
Example 3: Interactive Particle System
1```p5js
2let particles = [];
3
4sketch.setup = function() {
5 sketch.createCanvas(500, 400);
6};
7
8sketch.draw = function() {
9 sketch.background(20, 20, 40, 25); // Trailing effect
10
11 // Create new particle on mouse press
12 if (sketch.mouseIsPressed) {
13 particles.push({
14 x: sketch.mouseX,
15 y: sketch.mouseY,
16 vx: sketch.random(-2, 2),
17 vy: sketch.random(-2, 2),
18 life: 255
19 });
20 }
21
22 // Update and draw particles
23 for (let i = particles.length - 1; i >= 0; i--) {
24 let p = particles[i];
25
26 p.x += p.vx;
27 p.y += p.vy;
28 p.life -= 2;
29
30 sketch.fill(100, 200, 255, p.life);
31 sketch.noStroke();
32 sketch.ellipse(p.x, p.y, 8, 8);
33
34 // Remove dead particles
35 if (p.life < 0) {
36 particles.splice(i, 1);
37 }
38 }
39
40 // Instructions
41 sketch.fill(255);
42 sketch.text('Click and drag to create particles', 10, 20);
43};
44```
Result: (Click and drag to create particles)
Example 4: Algorithm Visualization (Sorting)
1```p5js
2let values = [];
3let i = 0;
4let j = 0;
5
6sketch.setup = function() {
7 sketch.createCanvas(600, 300);
8
9 // Initialize random array
10 for (let k = 0; k < 50; k++) {
11 values[k] = sketch.random(sketch.height - 40);
12 }
13
14 sketch.frameRate(10); // Slow down to see sorting
15};
16
17sketch.draw = function() {
18 sketch.background(240);
19
20 // Bubble sort step
21 if (i < values.length) {
22 if (j < values.length - i - 1) {
23 if (values[j] > values[j + 1]) {
24 let temp = values[j];
25 values[j] = values[j + 1];
26 values[j + 1] = temp;
27 }
28 j++;
29 } else {
30 j = 0;
31 i++;
32 }
33 }
34
35 // Draw bars
36 let barWidth = sketch.width / values.length;
37 for (let k = 0; k < values.length; k++) {
38 if (k === j) {
39 sketch.fill(255, 100, 100); // Highlight current comparison
40 } else if (k >= values.length - i) {
41 sketch.fill(100, 255, 100); // Sorted portion
42 } else {
43 sketch.fill(150, 150, 250);
44 }
45 sketch.rect(k * barWidth, sketch.height - values[k], barWidth - 2, values[k]);
46 }
47
48 // Status
49 sketch.fill(0);
50 sketch.text('Bubble Sort Visualization', 10, 20);
51};
52```
Result: (Watch the sorting algorithm in action)
Example 5: Network Graph
1```p5js
2let nodes = [];
3let connections = [];
4
5sketch.setup = function() {
6 sketch.createCanvas(500, 500);
7
8 // Create nodes
9 for (let i = 0; i < 8; i++) {
10 nodes.push({
11 x: sketch.random(50, sketch.width - 50),
12 y: sketch.random(50, sketch.height - 50),
13 vx: sketch.random(-1, 1),
14 vy: sketch.random(-1, 1)
15 });
16 }
17
18 // Create random connections
19 for (let i = 0; i < 12; i++) {
20 let a = sketch.floor(sketch.random(nodes.length));
21 let b = sketch.floor(sketch.random(nodes.length));
22 if (a !== b) {
23 connections.push([a, b]);
24 }
25 }
26};
27
28sketch.draw = function() {
29 sketch.background(255);
30
31 // Update node positions
32 for (let node of nodes) {
33 node.x += node.vx;
34 node.y += node.vy;
35
36 // Bounce off edges
37 if (node.x < 30 || node.x > sketch.width - 30) node.vx *= -1;
38 if (node.y < 30 || node.y > sketch.height - 30) node.vy *= -1;
39 }
40
41 // Draw connections
42 sketch.stroke(200);
43 sketch.strokeWeight(1);
44 for (let conn of connections) {
45 let nodeA = nodes[conn[0]];
46 let nodeB = nodes[conn[1]];
47 sketch.line(nodeA.x, nodeA.y, nodeB.x, nodeB.y);
48 }
49
50 // Draw nodes
51 sketch.noStroke();
52 sketch.fill(100, 150, 250);
53 for (let node of nodes) {
54 sketch.ellipse(node.x, node.y, 20, 20);
55 }
56};
57```
Result: (Animated network graph)
Notes
- P5.js sketches are interactive by default
- Use
sketch.prefix for all P5.js functions frameRate()controls animation speednoLoop()for static drawings- Mouse/keyboard events:
mousePressed(),keyPressed(), etc.
Gotchas/Warnings
- ⚠️ Performance: Complex animations can be slow - optimize draw loop
- ⚠️ Canvas size: Large canvases impact performance
- ⚠️ Memory: Clean up arrays and objects to prevent memory leaks
- ⚠️ Syntax: Must use
sketch.prefix for all P5.js functions in Hugo
Related Snippets
- Architecture Diagrams (C4 Model)
Create system architecture diagrams using C4 model with Mermaid - Chart.js Bar Chart
Create bar charts for data visualization - Graphviz DOT Diagrams
Create complex graph layouts with Graphviz DOT language - KaTeX Math Examples and Tips
Comprehensive guide to KaTeX math notation with examples and tips - Mermaid Arbitrary Graphs
Create arbitrary graphs and networks with Mermaid - Mermaid Block Diagrams
Create block diagrams for system architecture with Mermaid - Mermaid Charts (Pie, Bar, Line)
Create pie charts, bar charts, and line charts with Mermaid - Mermaid Class Diagrams (UML)
Create UML class diagrams with Mermaid - Mermaid Entity Relationship Diagrams
Create Entity Relationship Diagrams (ERD) with Mermaid - Mermaid Flowchart
Create flowcharts and decision trees with Mermaid - Mermaid Gantt Chart
Create Gantt charts for project timelines and scheduling - Mermaid Git Diagrams
Create Git branch and commit diagrams with Mermaid - Mermaid Kanban Boards
Create Kanban boards for project management with Mermaid - Mermaid Mindmaps
Create mindmaps for brainstorming and organizing ideas with Mermaid - Mermaid Packet Diagrams
Create packet diagrams for network protocols with Mermaid - Mermaid Quadrant Charts
Create quadrant charts for prioritization with Mermaid - Mermaid Radar Charts
Create radar charts for multi-dimensional comparisons with Mermaid - Mermaid Requirement Diagrams
Create requirement diagrams for system requirements with Mermaid - Mermaid Sankey Diagrams
Create Sankey diagrams for flow visualization with Mermaid - Mermaid Sequence Diagram
Create sequence diagrams for interactions and API flows - Mermaid State Diagrams
Create state diagrams and state machines with Mermaid - Mermaid Timeline Diagrams
Create timeline diagrams for chronological events with Mermaid - Mermaid Treemap Diagrams
Create treemap diagrams for hierarchical data visualization with Mermaid - Mermaid User Journey Diagrams
Create user journey maps with Mermaid - Mermaid ZenUML Diagrams
Create ZenUML sequence diagrams with Mermaid