or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

color-system.mdcore-structure.mddom-manipulation.mddrawing-shapes.mdevents-input.mdimage-processing.mdindex.mdio-data.mdmath-vectors.mdtransforms.mdtypography.mdutilities.mdwebgl-3d.md

index.mddocs/

0

# p5.js

1

2

p5.js is a comprehensive JavaScript creative coding library that provides a complete toolkit for interactive web-based art, visualizations, and multimedia experiences. Built as an accessible alternative to the Processing programming language, it offers drawing functionalities, canvas management, interaction handling, animation capabilities, and multimedia support through an intuitive API that emphasizes creative expression and exploratory programming.

3

4

## Package Information

5

6

- **Package Name**: p5

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install p5`

10

11

## Core Imports

12

13

ES Modules:

14

```javascript

15

import p5 from 'p5';

16

```

17

18

CommonJS:

19

```javascript

20

const p5 = require('p5');

21

```

22

23

For global mode (browser):

24

```html

25

<script src="https://cdn.jsdelivr.net/npm/p5@1.11.10/lib/p5.min.js"></script>

26

```

27

28

## Basic Usage

29

30

**Global Mode (Browser):**

31

```javascript

32

function setup() {

33

createCanvas(400, 400);

34

}

35

36

function draw() {

37

background(220);

38

circle(mouseX, mouseY, 80);

39

}

40

```

41

42

**Instance Mode:**

43

```javascript

44

import p5 from 'p5';

45

46

const sketch = (p) => {

47

p.setup = () => {

48

p.createCanvas(400, 400);

49

};

50

51

p.draw = () => {

52

p.background(220);

53

p.circle(p.mouseX, p.mouseY, 80);

54

};

55

};

56

57

new p5(sketch);

58

```

59

60

## Architecture

61

62

p5.js is built around several key architectural patterns:

63

64

- **Sketch Lifecycle**: Three main functions (`preload()`, `setup()`, `draw()`) control execution flow

65

- **Global vs Instance Mode**: Functions can be available globally or bound to a p5 instance

66

- **Rendering System**: Unified API that works with 2D canvas, WebGL, and off-screen graphics

67

- **Event System**: Comprehensive mouse, keyboard, touch, and device motion event handling

68

- **Vector Math**: Complete 2D/3D vector operations through p5.Vector class

69

- **Color System**: Flexible color representation supporting RGB, HSB, HSL color spaces

70

71

## Capabilities

72

73

### Core Structure & Environment

74

75

Essential sketch lifecycle functions, canvas creation, and environment control. This forms the foundation of every p5.js application.

76

77

```javascript { .api }

78

function preload() { /* Called once to load assets before sketch runs */ }

79

function setup() { /* Called once when sketch begins running */ }

80

function draw() { /* Called repeatedly while sketch runs */ }

81

82

function createCanvas(w, h, renderer) { /* Create main drawing canvas */ }

83

function background(...args) { /* Set background color */ }

84

85

// Environment variables

86

frameCount; // Number of frames since sketch started

87

width, height; // Canvas dimensions

88

mouseX, mouseY; // Current mouse position

89

```

90

91

[Core Structure & Environment](./core-structure.md)

92

93

### 2D Drawing & Shapes

94

95

Complete 2D drawing capabilities including primitives, curves, custom shapes, and drawing attributes.

96

97

```javascript { .api }

98

function circle(x, y, diameter) { /* Draw circle */ }

99

function rect(x, y, w, h, tl, tr, br, bl) { /* Draw rectangle */ }

100

function line(x1, y1, x2, y2) { /* Draw line */ }

101

function bezier(x1, y1, x2, y2, x3, y3, x4, y4) { /* Draw Bezier curve */ }

102

103

function fill(...args) { /* Set fill color */ }

104

function stroke(...args) { /* Set stroke color */ }

105

function strokeWeight(weight) { /* Set stroke thickness */ }

106

```

107

108

[2D Drawing & Shapes](./drawing-shapes.md)

109

110

### Color System

111

112

Comprehensive color handling with multiple color spaces, color manipulation, and advanced features like blending modes.

113

114

```javascript { .api }

115

function color(...args) { /* Create p5.Color object */ }

116

function colorMode(mode, max1, max2, max3, maxA) { /* Set color interpretation mode */ }

117

function lerpColor(c1, c2, amt) { /* Interpolate between colors */ }

118

119

// Color extraction

120

function red(color) { /* Extract red component */ }

121

function green(color) { /* Extract green component */ }

122

function blue(color) { /* Extract blue component */ }

123

function alpha(color) { /* Extract alpha component */ }

124

```

125

126

[Color System](./color-system.md)

127

128

### Math & Vector Operations

129

130

Mathematical functions, trigonometry, random number generation, noise, and the comprehensive p5.Vector class for position/velocity calculations.

131

132

```javascript { .api }

133

class p5.Vector {

134

constructor(x, y, z) { /* Create vector */ }

135

add(x, y, z) { /* Add to vector */ }

136

mult(scalar) { /* Multiply by scalar */ }

137

mag() { /* Calculate magnitude */ }

138

normalize() { /* Normalize to unit length */ }

139

140

static random2D() { /* Random 2D unit vector */ }

141

static fromAngle(angle, length) { /* Create from angle */ }

142

}

143

144

function random(min, max) { /* Generate random number */ }

145

function noise(x, y, z) { /* Perlin noise value */ }

146

function map(value, start1, stop1, start2, stop2) { /* Re-map number range */ }

147

```

148

149

[Math & Vector Operations](./math-vectors.md)

150

151

### Transform System

152

153

Coordinate transformations including translation, rotation, scaling, and matrix operations for advanced graphics.

154

155

```javascript { .api }

156

function translate(x, y, z) { /* Translate coordinate system */ }

157

function rotate(angle) { /* Rotate coordinate system */ }

158

function scale(s, y, z) { /* Scale coordinate system */ }

159

function push() { /* Save current transform state */ }

160

function pop() { /* Restore previous transform state */ }

161

```

162

163

[Transform System](./transforms.md)

164

165

### Event Handling & Input

166

167

Complete event system for mouse, keyboard, touch, and device motion interactions with both callback functions and polling.

168

169

```javascript { .api }

170

// Event callback functions

171

function mousePressed() { /* Called when mouse button pressed */ }

172

function keyPressed() { /* Called when key pressed */ }

173

function touchStarted() { /* Called when touch begins */ }

174

175

// Input state variables

176

mouseX, mouseY; // Current mouse position

177

mouseButton; // Current pressed button (LEFT, RIGHT, CENTER)

178

key; // Most recently pressed key

179

keyCode; // Numeric code of pressed key

180

touches; // Array of current touch points

181

```

182

183

[Event Handling & Input](./events-input.md)

184

185

### Image Processing

186

187

Image loading, display, manipulation, filtering, and pixel-level operations for creative image effects.

188

189

```javascript { .api }

190

function loadImage(path, successCallback, failureCallback) { /* Load image */ }

191

function image(img, x, y, width, height) { /* Display image */ }

192

function tint(...args) { /* Apply color tint to images */ }

193

function filter(filterType, filterParam) { /* Apply filter to canvas */ }

194

195

function get(x, y, w, h) { /* Get pixel/region from canvas */ }

196

function set(x, y, color) { /* Set pixel color */ }

197

function loadPixels() { /* Load pixel array for manipulation */ }

198

function updatePixels() { /* Update canvas from pixel array */ }

199

```

200

201

[Image Processing](./image-processing.md)

202

203

### I/O & Data Loading

204

205

File loading capabilities for JSON, XML, images, fonts, and other assets, plus data export functionality.

206

207

```javascript { .api }

208

function loadJSON(path, callback, errorCallback) { /* Load JSON data */ }

209

function loadStrings(filename, callback) { /* Load text file as array */ }

210

function loadTable(filename, options, callback) { /* Load CSV/TSV data */ }

211

function loadFont(path, callback) { /* Load font file */ }

212

213

function save(objectOrFilename, filename) { /* Save data to file */ }

214

function saveCanvas(filename, extension) { /* Save canvas as image */ }

215

```

216

217

[I/O & Data Loading](./io-data.md)

218

219

### Typography

220

221

Text rendering, font loading, text measurement, and typography control for creative text applications.

222

223

```javascript { .api }

224

function text(str, x, y, x2, y2) { /* Draw text to canvas */ }

225

function textFont(font, size) { /* Set text font */ }

226

function textSize(size) { /* Set text size */ }

227

function textAlign(horizAlign, vertAlign) { /* Set text alignment */ }

228

function textWidth(str) { /* Calculate text width */ }

229

230

class p5.Font {

231

/* Font object with glyph and measurement capabilities */

232

}

233

```

234

235

[Typography](./typography.md)

236

237

### DOM Manipulation

238

239

Create and control HTML elements, form inputs, and integrate p5.js with web page DOM for interactive applications.

240

241

```javascript { .api }

242

function select(selector, container) { /* Select DOM element */ }

243

function createElement(tag, content) { /* Create generic element */ }

244

function createButton(label, value) { /* Create button element */ }

245

function createSlider(min, max, value, step) { /* Create range slider */ }

246

function createInput(value, type) { /* Create text input */ }

247

248

class p5.Element {

249

/* DOM element wrapper with p5-specific methods */

250

}

251

```

252

253

[DOM Manipulation](./dom-manipulation.md)

254

255

### WebGL & 3D Graphics

256

257

Complete 3D graphics system with primitives, lighting, materials, shaders, cameras, and advanced WebGL features.

258

259

```javascript { .api }

260

function createCanvas(w, h, WEBGL) { /* Create 3D canvas */ }

261

function box(width, height, depth) { /* Draw 3D box */ }

262

function sphere(radius, detailX, detailY) { /* Draw sphere */ }

263

264

function ambientLight(...args) { /* Create ambient light */ }

265

function directionalLight(...args) { /* Create directional light */ }

266

function ambientMaterial(...args) { /* Set ambient material */ }

267

268

class p5.Camera { /* 3D camera control */ }

269

class p5.Shader { /* GLSL shader program wrapper */ }

270

```

271

272

[WebGL & 3D Graphics](./webgl-3d.md)

273

274

### Utility Functions

275

276

Helpful utility functions for array manipulation, string processing, data conversion, and time/date operations.

277

278

```javascript { .api }

279

function shuffle(array) { /* Randomize array order */ }

280

function sort(list, count) { /* Sort array */ }

281

function join(list, separator) { /* Join array into string */ }

282

function split(value, delim) { /* Split string into array */ }

283

284

function int(str, base) { /* Convert to integer */ }

285

function float(str) { /* Convert to float */ }

286

function str(n) { /* Convert to string */ }

287

288

function millis() { /* Milliseconds since sketch start */ }

289

function year() { /* Current year */ }

290

```

291

292

[Utility Functions](./utilities.md)

293

294

## Types

295

296

```javascript { .api }

297

class p5 {

298

constructor(sketch, node);

299

remove();

300

}

301

302

class p5.Color {

303

/* Color representation with RGB, HSB, HSL support */

304

}

305

306

class p5.Image {

307

width, height; // Image dimensions

308

pixels; // Pixel array

309

/* Image manipulation methods */

310

}

311

312

class p5.Graphics {

313

/* Off-screen graphics buffer with same API as main canvas */

314

}

315

316

class p5.StringDict {

317

/* Dictionary for storing string key-value pairs */

318

constructor(key, value);

319

size(); // Number of key-value pairs

320

hasKey(key); // Check if key exists

321

get(key); // Get value for key

322

set(key, value); // Set value for key

323

create(key, value); // Create new key-value pair

324

clear(); // Remove all pairs

325

remove(key); // Remove specific pair

326

print(); // Log all pairs to console

327

saveTable(filename); // Save as CSV file

328

saveJSON(filename); // Save as JSON file

329

}

330

331

class p5.NumberDict {

332

/* Dictionary for storing number key-value pairs with mathematical operations */

333

constructor(key, value);

334

size(); // Number of key-value pairs

335

hasKey(key); // Check if key exists

336

get(key); // Get value for key

337

set(key, value); // Set value for key

338

create(key, value); // Create new key-value pair

339

clear(); // Remove all pairs

340

remove(key); // Remove specific pair

341

print(); // Log all pairs to console

342

saveTable(filename); // Save as CSV file

343

saveJSON(filename); // Save as JSON file

344

add(key, amount); // Add to value at key

345

sub(key, amount); // Subtract from value at key

346

mult(key, amount); // Multiply value at key

347

div(key, amount); // Divide value at key

348

minValue(); // Find minimum value

349

maxValue(); // Find maximum value

350

minKey(); // Find minimum key

351

maxKey(); // Find maximum key

352

}

353

```