0
# Core Structure & Environment
1
2
Essential sketch lifecycle functions, canvas creation, environment control, and system variables that form the foundation of every p5.js application.
3
4
## Capabilities
5
6
### Sketch Lifecycle
7
8
The three main functions that control p5.js sketch execution flow.
9
10
```javascript { .api }
11
/**
12
* Called once to load assets before the sketch runs
13
* Functions like loadImage(), loadFont(), etc. called here will block setup()
14
* until they complete loading
15
*/
16
function preload() {}
17
18
/**
19
* Called once when the sketch begins running
20
* Used to perform setup tasks like creating canvas and initializing variables
21
*/
22
function setup() {}
23
24
/**
25
* Called repeatedly while the sketch runs (draw loop)
26
* Default attempts 60 fps, can be controlled with frameRate()
27
*/
28
function draw() {}
29
```
30
31
### Draw Loop Control
32
33
Functions to control sketch execution and animation loop.
34
35
```javascript { .api }
36
/**
37
* Stops the draw loop - draw() will no longer be called
38
*/
39
function noLoop();
40
41
/**
42
* Resumes the draw loop after noLoop() was called
43
*/
44
function loop();
45
46
/**
47
* Returns whether the draw loop is currently active
48
* @returns {boolean} True if draw() is being called repeatedly
49
*/
50
function isLooping();
51
52
/**
53
* Executes draw() n times (default 1) even when not looping
54
* @param {number} [n=1] - Number of times to call draw()
55
*/
56
function redraw(n);
57
```
58
59
### Canvas Creation & Management
60
61
Functions for creating and managing the main drawing canvas and off-screen graphics.
62
63
```javascript { .api }
64
/**
65
* Creates the main drawing canvas
66
* @param {number} w - Width in pixels
67
* @param {number} h - Height in pixels
68
* @param {string} [renderer] - P2D (default) or WEBGL for 3D
69
* @param {HTMLCanvasElement} [canvas] - Existing canvas element to use
70
*/
71
function createCanvas(w, h, renderer, canvas);
72
73
/**
74
* Resizes the canvas dimensions
75
* @param {number} w - New width in pixels
76
* @param {number} h - New height in pixels
77
* @param {boolean} [noRedraw=false] - If true, don't redraw after resize
78
*/
79
function resizeCanvas(w, h, noRedraw);
80
81
/**
82
* Removes the default canvas (for DOM-only sketches)
83
*/
84
function noCanvas();
85
86
/**
87
* Creates an off-screen graphics buffer with same API as main canvas
88
* @param {number} w - Width in pixels
89
* @param {number} h - Height in pixels
90
* @param {string} [renderer] - P2D (default) or WEBGL
91
* @param {HTMLCanvasElement} [canvas] - Existing canvas element
92
* @returns {p5.Graphics} Graphics buffer object
93
*/
94
function createGraphics(w, h, renderer, canvas);
95
96
/**
97
* Creates a WebGL framebuffer for off-screen rendering
98
* @param {object} [options] - Framebuffer options
99
* @returns {p5.Framebuffer} Framebuffer object
100
*/
101
function createFramebuffer(options);
102
```
103
104
### Transform State Management
105
106
Functions to save and restore drawing states including transforms and styles.
107
108
```javascript { .api }
109
/**
110
* Saves current drawing state (transforms, fill, stroke, etc.)
111
* Must be paired with pop()
112
*/
113
function push();
114
115
/**
116
* Restores previous drawing state saved with push()
117
*/
118
function pop();
119
```
120
121
### System Variables
122
123
Key variables that provide information about the sketch state and dimensions.
124
125
```javascript { .api }
126
/**
127
* Number of frames since the sketch started
128
* Increments by 1 each time draw() is called
129
* @type {number}
130
*/
131
var frameCount;
132
133
/**
134
* Time in milliseconds for the last frame
135
* Useful for frame-rate independent animation
136
* @type {number}
137
*/
138
var deltaTime;
139
140
/**
141
* Current width of the canvas in pixels
142
* @type {number}
143
*/
144
var width;
145
146
/**
147
* Current height of the canvas in pixels
148
* @type {number}
149
*/
150
var height;
151
152
/**
153
* Whether the browser window currently has focus
154
* @type {boolean}
155
*/
156
var focused;
157
```
158
159
### Environment Information
160
161
Variables and functions for accessing browser and device information.
162
163
```javascript { .api }
164
/**
165
* Browser viewport width in pixels
166
* @type {number}
167
*/
168
var windowWidth;
169
170
/**
171
* Browser viewport height in pixels
172
* @type {number}
173
*/
174
var windowHeight;
175
176
/**
177
* Screen resolution width in pixels
178
* @type {number}
179
*/
180
var displayWidth;
181
182
/**
183
* Screen resolution height in pixels
184
* @type {number}
185
*/
186
var displayHeight;
187
188
/**
189
* Current WebGL version being used ('webgl' or 'webgl2')
190
* Only set when using WEBGL renderer
191
* @type {string}
192
*/
193
var webglVersion;
194
```
195
196
### Environment Control Functions
197
198
Functions for controlling frame rate, display settings, and getting page information.
199
200
```javascript { .api }
201
/**
202
* Set target frame rate or get current frame rate
203
* @param {number} [fps] - Target frames per second (default 60)
204
* @returns {number} Current frame rate when called without arguments
205
*/
206
function frameRate(fps);
207
208
/**
209
* Set/get pixel density for high DPI displays
210
* @param {number} [density] - Pixel density multiplier
211
* @returns {number} Current pixel density when called without arguments
212
*/
213
function pixelDensity(density);
214
215
/**
216
* Enter/exit fullscreen mode or get fullscreen state
217
* @param {boolean} [val] - True to enter fullscreen, false to exit
218
* @returns {boolean} Current fullscreen state when called without arguments
219
*/
220
function fullscreen(val);
221
222
/**
223
* Get the current page URL
224
* @returns {string} Current page URL
225
*/
226
function getURL();
227
228
/**
229
* Get URL path as an array of strings
230
* @returns {string[]} Array of path segments
231
*/
232
function getURLPath();
233
234
/**
235
* Get URL parameters as an object
236
* @returns {object} Object with parameter names as keys
237
*/
238
function getURLParams();
239
```
240
241
### Rendering Control
242
243
Functions for controlling rendering behavior and accessing the graphics context.
244
245
```javascript { .api }
246
/**
247
* Set the pixel blending mode for drawing operations
248
* @param {string} mode - Blend mode (BLEND, ADD, MULTIPLY, etc.)
249
*/
250
function blendMode(mode);
251
252
/**
253
* Clear the WebGL depth buffer to specified depth
254
* @param {number} [depth=1] - Depth value to clear to (0-1)
255
*/
256
function clearDepth(depth);
257
258
/**
259
* Direct access to the canvas 2D context or WebGL context
260
* @type {CanvasRenderingContext2D|WebGLRenderingContext}
261
*/
262
var drawingContext;
263
```
264
265
### Cursor Control
266
267
Functions for controlling the mouse cursor appearance.
268
269
```javascript { .api }
270
/**
271
* Set the cursor appearance
272
* @param {string} type - Cursor type (ARROW, CROSS, HAND, MOVE, TEXT, WAIT)
273
* @param {number} [x] - Horizontal offset for custom cursor
274
* @param {number} [y] - Vertical offset for custom cursor
275
*/
276
function cursor(type, x, y);
277
278
/**
279
* Hide the mouse cursor
280
*/
281
function noCursor();
282
```
283
284
### Console Output
285
286
Enhanced console output function.
287
288
```javascript { .api }
289
/**
290
* Output to console (enhanced console.log)
291
* @param {...*} args - Values to print
292
*/
293
function print(...args);
294
```
295
296
### Sketch Removal
297
298
Function to completely remove the sketch from the page.
299
300
```javascript { .api }
301
/**
302
* Removes the sketch from the web page
303
* Stops draw loop and removes all HTML elements created by the sketch
304
*/
305
function remove();
306
```
307
308
## Usage Examples
309
310
**Basic Sketch Structure:**
311
```javascript
312
let counter = 0;
313
314
function setup() {
315
createCanvas(400, 300);
316
frameRate(30); // Set to 30 fps
317
}
318
319
function draw() {
320
background(220);
321
322
// Frame-rate independent animation
323
counter += deltaTime * 0.001; // Increment by seconds
324
325
circle(200 + sin(counter) * 100, 150, 50);
326
327
// Display frame info
328
text(`Frame: ${frameCount}`, 10, 20);
329
text(`FPS: ${frameRate().toFixed(1)}`, 10, 40);
330
}
331
```
332
333
**State Management with Push/Pop:**
334
```javascript
335
function draw() {
336
background(220);
337
338
// Draw in normal coordinate system
339
fill('red');
340
rect(10, 10, 50, 50);
341
342
push(); // Save current state
343
translate(100, 100);
344
rotate(PI / 4);
345
fill('blue');
346
rect(0, 0, 50, 50); // This rectangle is rotated
347
pop(); // Restore state
348
349
// Back to normal coordinate system
350
fill('green');
351
rect(200, 10, 50, 50);
352
}
353
```
354
355
**Off-screen Graphics:**
356
```javascript
357
let buffer;
358
359
function setup() {
360
createCanvas(400, 300);
361
buffer = createGraphics(200, 200);
362
}
363
364
function draw() {
365
// Draw to off-screen buffer
366
buffer.background(100);
367
buffer.fill('yellow');
368
buffer.circle(mouseX * 0.5, mouseY * 0.5, 50);
369
370
// Display buffer on main canvas
371
background(220);
372
image(buffer, 0, 0);
373
image(buffer, 200, 0); // Show twice
374
}
375
```