Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. P5js

Learn P5js - 10 Code Examples & CST Typing Practice Test

p5.js is a JavaScript library designed to make coding accessible for artists, designers, and beginners. It provides an intuitive way to create graphics, animations, and interactive content on the web using a friendly API inspired by Processing.

View all 10 P5js code examples →
Hello World in p5.jsMoving CircleBouncing BallColorful RectanglesMouse Follow CircleRandom StarsGrowing CircleRotating LineRandom WalkInteractive Rectangle

Learn P5JS with Real Code Examples

Updated Nov 26, 2025

Explain

p5.js simplifies drawing shapes, handling events, and creating animations in JavaScript.

It provides a high-level API for 2D and 3D graphics, sound, and video.

The library encourages creative coding and visual experimentation.

It abstracts complex web APIs like Canvas and WebGL for easy use.

p5.js can run directly in a browser without setup.

Core Features

`setup()` and `draw()` loop for initialization and animation

Functions for shapes: `rect()`, `ellipse()`, `line()`

Color and style management: `fill()`, `stroke()`

Mouse and keyboard event callbacks

Integration with DOM and HTML elements

Basic Concepts Overview

Sketch - a p5.js program containing `setup()` and `draw()`

`setup()` - runs once for initialization

`draw()` - runs continuously for animation

Shapes - `rect()`, `ellipse()`, `line()` to draw graphics

Events - `mousePressed()`, `keyPressed()` for interactivity

Project Structure

Single HTML file with embedded JS script

Optional external JS files for modularity

Optional assets folder for images, sounds, etc.

Sketch code usually global in scope

Libraries included as needed

Building Workflow

Create an HTML file and link p5.js

Define `setup()` for canvas and initial setup

Define `draw()` for continuous rendering

Add interactive callbacks as needed

Test and iterate in a web browser

Difficulty Use Cases

Beginner: draw static shapes and colors

Intermediate: animate objects, handle events

Advanced: build interactive multimedia sketches

Expert: integrate with WebGL, ML libraries, or APIs

Architect: design complex interactive experiences or visualizations

Comparisons

p5.js vs Processing -> JavaScript vs Java, both beginner-friendly

p5.js vs Three.js -> p5.js simpler 2D/3D, Three.js more advanced 3D

p5.js vs D3.js -> p5.js creative coding, D3.js data visualization

p5.js vs vanilla Canvas -> p5.js easier, abstracts low-level details

p5.js vs PixiJS -> p5.js general creative coding, PixiJS optimized for WebGL graphics

Versioning Timeline

2014 - p5.js created by Lauren McCarthy

2015 - Initial release and community adoption

2016 - p5.sound library released

2018 - Improved documentation and tutorials

2020-2025 - Active community growth and library updates

Glossary

Sketch - a p5.js program

Canvas - drawing area

draw() - loop function for rendering

setup() - initialization function

Callback - function triggered by an event

Installation Setup

Include p5.js via CDN or download library files

Link p5.js in HTML `<script>` tags

Optional: include p5.dom.js or p5.sound.js for extended features

Use a text editor or online editor like editor.p5js.org

Open HTML file in a web browser to run sketches

Environment Setup

Install any code editor (VSCode, Sublime, etc.)

Download p5.js or link via CDN

Optional local server for testing

Organize assets and code files

Open HTML file in browser to test sketches

Config Files

HTML file linking p5.js

Optional JS files for modular code

Assets folder for images, sounds, videos

README or documentation

Optional CSS for page styling

Cli Commands

No CLI required; runs in browser

Optional: use local server to host sketches

Live reload with editor.p5js.org

Debug via browser console

Export sketches via HTML/JS bundle

Internationalization

Supports Unicode characters in canvas

Text can be rendered in multiple languages

Event handling works globally

Assets can include local content

Community examples in various languages

Accessibility

Browser-based, no installation required

Keyboard and mouse accessible

Text-to-speech or sound libraries possible

Open-source and widely documented

Works on most modern devices

Ui Styling

Canvas for visuals

Optional DOM elements via p5.dom

Styling via `fill()`, `stroke()`, `textSize()`

Can integrate HTML/CSS for UI

Supports interactive controls like sliders and buttons

State Management

Global variables typically store state

`draw()` updates state every frame

Event handlers modify state interactively

Objects and classes help manage complex sketches

Use `push()` and `pop()` to manage transformations

Data Management

Variables, arrays, and objects hold data

Load external data via `loadJSON()`, `loadTable()`, etc.

Images and sounds stored in assets folder

Data-driven sketches possible

State updated in `draw()` or callbacks

Architecture

Core library built on top of JavaScript and HTML5 Canvas/WebGL

`setup()` runs once, `draw()` loops continuously

State is typically global or object-oriented

Uses event-driven programming for interactivity

Extensible via plugins and additional p5 libraries

Rendering Model

Uses HTML5 Canvas or WebGL for drawing

`draw()` loop updates canvas every frame

Event-driven for user interactions

State stored in variables or objects

Supports layering and transformations

Architectural Patterns

Global sketch structure with `setup()` and `draw()`

Event callbacks for interactivity

Optional modular code in external JS files

Animation loops handled automatically

Extensible via plugins and libraries

Real World Architectures

Educational platforms and coding schools

Online art installations and exhibitions

Web-based games and interactive storytelling

Data visualization demos

Creative coding workshops

Design Principles

Accessibility for beginners and artists

Simplify web-based graphics programming

High-level API for 2D/3D visuals

Encourage experimentation and creativity

Open-source and community-driven development

Scalability Guide

Small: simple drawing sketches

Medium: interactive sketches and games

Large: multimedia and 3D projects

Enterprise: educational platforms and demos

Global: online sharing and creative coding community

Migration Guide

Move HTML/JS files between projects

Update CDN links for latest version

Test sketches in new browser versions

Adapt external library usage as needed

Refactor code for modularity if required

Performance Notes

Simple sketches run efficiently in browsers

Complex sketches with many objects may lag

Avoid excessive DOM manipulations in `draw()`

Use `frameRate()` to control loop speed

Consider optimization for real-time animations

Security Notes

Runs in browser sandbox, so minimal security risk

Be cautious when loading external assets

Avoid injecting untrusted scripts

Use HTTPS for secure asset loading

Monitor memory usage for heavy multimedia sketches

Monitoring Analytics

Use browser console for debugging

Monitor FPS and performance in complex sketches

Log user interactions for analysis

Test across devices and browsers

Document behavior for iterative improvements

Code Quality

Organize sketches with functions and classes

Minimize global variables where possible

Comment code for clarity

Test sketches incrementally

Optimize animation loops for performance

Practical Examples

Animating bouncing balls on canvas

Drawing interactive fractals

Creating generative art patterns

Visualizing data with graphs and shapes

Building simple browser-based games

Troubleshooting

Ensure canvas size matches expectations

Check that scripts are loaded correctly in HTML

Use `console.log()` to debug variables

Remember `draw()` loops continuously; manage state carefully

Test interactive events to confirm they fire correctly

Testing Guide

Test sketches in multiple browsers

Verify interactivity and responsiveness

Use browser console for debugging

Check performance for animations

Ensure assets load correctly

Deployment Options

Host HTML/JS files on a web server

Share via GitHub Pages

Embed in educational platforms

Publish interactive artworks online

Include in multimedia presentations

Tools Ecosystem

p5.js core library

p5.sound for audio

p5.dom for HTML element manipulation

p5.editor online platform

Community-contributed libraries and plugins

Integrations

Embed p5.js sketches in web pages

Integrate with APIs for data visualization

Use with machine learning libraries like ml5.js

Combine with other JavaScript frameworks

Export sketches as images, GIFs, or videos

Productivity Tips

Start with small sketches

Reuse code and functions

Leverage community examples

Test continuously in browser

Focus on visual clarity and interaction

Challenges

Managing state in continuous animation loops

Ensuring performance for many objects

Debugging event-driven interactivity

Integrating multimedia assets correctly

Transitioning from simple sketches to complex projects

Learning Path

Learn basic JavaScript syntax

Understand `setup()` and `draw()`

Experiment with shapes, colors, and animation

Handle events like mouse and keyboard

Create interactive sketches and small projects

Skill Improvement Plan

Week 1: Draw shapes and apply colors

Week 2: Animate objects and learn frame updates

Week 3: Handle mouse/keyboard events

Week 4: Work with images, sounds, and video

Week 5: Build interactive projects and mini-games

Interview Questions

What is the difference between `setup()` and `draw()` in p5.js?

How do you handle mouse and keyboard events in p5.js?

Explain the use of `createCanvas()`

How would you animate objects in p5.js?

What libraries extend p5.js functionality?

Cheat Sheet

createCanvas(width, height) - initialize drawing area

background(color) - set canvas background

fill(color) - set fill color for shapes

stroke(color) - set outline color for shapes

ellipse(x, y, w, h), rect(x, y, w, h) - draw shapes

Books

Getting Started with p5.js - Lauren McCarthy

Make: Getting Started with p5.js

Creative Coding with p5.js

Generative Design with p5.js

The Nature of Code

Tutorials

Getting Started with p5.js

Drawing and Animating Shapes

Handling Events and Interactivity

Working with Images, Sound, and Video

Building Interactive Projects and Games

Official Docs

https://p5js.org/reference/

https://p5js.org/

Community Links

p5.js Forum

Processing Foundation

p5.js GitHub repository

Creative Coding Slack/Discord

Online learning platforms like The Coding Train

Community Support

Official p5.js website and forums

Creative coding Slack/Discord communities

GitHub repository for p5.js

Tutorial blogs and YouTube channels

Processing Foundation educational resources

Monetization

Mostly educational and hobbyist use

Online courses and workshops

Interactive web projects for clients

Portfolio showcases for artists and developers

Digital art sales and NFT projects

Future Roadmap

Better performance optimizations

Expanded 3D and WebGL capabilities

More tutorials and learning resources

Improved mobile and accessibility support

Integration with ML and AI libraries for creative coding

When Not To Use

High-performance games requiring WebGL optimization

Enterprise web apps without graphical components

Backend server applications

Complex 3D graphics projects better suited for Three.js

Large-scale data visualization projects requiring D3.js features

Final Summary

p5.js is a beginner-friendly creative coding library for the web.

It simplifies drawing, animation, and interactivity in JavaScript.

Primarily used in education, art, and creative coding.

Supports multimedia, events, and extensible features.

Encourages experimentation and visual programming.

Faq

Is p5.js suitable for beginners? -> Yes, designed for accessibility

Can I use p5.js for 3D graphics? -> Yes, with WEBGL mode

Does it work in all browsers? -> Modern browsers supported

Do I need prior JS knowledge? -> Helpful but not strictly required

Are there extensions for sound or ML? -> Yes, p5.sound and ml5.js

Code Sample Descriptions

1

Hello World in p5.js

function setup() {
    createCanvas(400, 200);
    background(255);
    fill(0);
    textSize(32);
    text("Hello World", 100, 100);
}

A simple p5.js sketch that displays 'Hello World' in the browser canvas.

Let’s Try →
2

Moving Circle

let x = 0;
function setup() {
    createCanvas(400, 200);
}
function draw() {
    background(255);
    ellipse(x, 100, 50, 50);
    x += 2;
    if(x > width) x = 0;
}

A circle moving horizontally across the canvas.

Let’s Try →
3

Bouncing Ball

let x = 200, y = 100;
let xspeed = 3, yspeed = 2;
function setup() {
    createCanvas(400, 200);
}
function draw() {
    background(255);
    x += xspeed;
    y += yspeed;
    if(x > width || x < 0) xspeed *= -1;
    if(y > height || y < 0) yspeed *= -1;
    ellipse(x, y, 50, 50);
}

A ball bouncing off the edges of the canvas.

Let’s Try →
4

Colorful Rectangles

function setup() {
    createCanvas(400, 200);
    noLoop();
}
function draw() {
    for(let i=0; i<10; i++) {
        fill(random(255), random(255), random(255));
        rect(i*40, 50, 30, 100);
    }
}

Draws a series of colored rectangles.

Let’s Try →
5

Mouse Follow Circle

function setup() {
    createCanvas(400, 200);
}
function draw() {
    background(255);
    fill(0, 100, 255);
    ellipse(mouseX, mouseY, 50, 50);
}

A circle that follows the mouse cursor.

Let’s Try →
6

Random Stars

function setup() {
    createCanvas(400, 200);
    background(0);
}
function draw() {
    fill(255);
    ellipse(random(width), random(height), 2, 2);
}

Draws random stars on the canvas every frame.

Let’s Try →
7

Growing Circle

let r = 10;
function setup() {
    createCanvas(400, 200);
}
function draw() {
    background(255);
    ellipse(width/2, height/2, r, r);
    r += 1;
    if(r > width) r = 10;
}

A circle that grows in size over time.

Let’s Try →
8

Rotating Line

let angle = 0;
function setup() {
    createCanvas(400, 200);
}
function draw() {
    background(255);
    translate(width/2, height/2);
    line(0, 0, 100*cos(angle), 100*sin(angle));
    angle += 0.05;
}

A line rotating around the center of the canvas.

Let’s Try →
9

Random Walk

let x, y;
function setup() {
    createCanvas(400, 200);
    x = width/2;
    y = height/2;
    background(255);
}
function draw() {
    stroke(0);
    x += random(-5, 5);
    y += random(-5, 5);
    point(x, y);
}

A point performing a random walk across the canvas.

Let’s Try →
10

Interactive Rectangle

function setup() {
    createCanvas(400, 200);
}
function draw() {
    background(255);
    if(mouseIsPressed) {
        rect(150, 50, 100, 100);
    } else {
        rect(150, 50, 50, 50);
    }
}

Rectangle width changes when mouse is pressed.

Let’s Try →

Frequently Asked Questions about P5js

What is P5js?

p5.js is a JavaScript library designed to make coding accessible for artists, designers, and beginners. It provides an intuitive way to create graphics, animations, and interactive content on the web using a friendly API inspired by Processing.

What are the primary use cases for P5js?

Educational projects for teaching programming. Interactive art installations. Web-based animations and visualizations. Prototyping games and interactive experiences. Creative coding experiments

What are the strengths of P5js?

Easy to learn for beginners. Great for visual and interactive projects. Runs directly in browsers. Strong community and learning resources. Extensible via additional libraries (sound, DOM, ML)

What are the limitations of P5js?

Not optimized for high-performance applications. Limited to web/browser environment. Complex 3D graphics are harder than low-level WebGL. May require JavaScript knowledge for advanced features. Not ideal for enterprise-scale applications

How can I practice P5js typing speed?

CodeSpeedTest offers 10+ real P5js code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.