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

math-vectors.mddocs/

0

# Math & Vector Operations

1

2

Mathematical functions, trigonometry, random number generation, noise functions, and the comprehensive p5.Vector class for position, velocity, and acceleration calculations in 2D and 3D space.

3

4

## Capabilities

5

6

### Basic Mathematical Functions

7

8

Core mathematical operations and utilities.

9

10

```javascript { .api }

11

/**

12

* Calculate absolute value

13

* @param {number} n - Input number

14

* @returns {number} Absolute value

15

*/

16

function abs(n);

17

18

/**

19

* Round up to nearest integer

20

* @param {number} n - Input number

21

* @returns {number} Ceiling value

22

*/

23

function ceil(n);

24

25

/**

26

* Round down to nearest integer

27

* @param {number} n - Input number

28

* @returns {number} Floor value

29

*/

30

function floor(n);

31

32

/**

33

* Round to nearest integer or specified decimal places

34

* @param {number} n - Input number

35

* @param {number} [decimals] - Number of decimal places

36

* @returns {number} Rounded value

37

*/

38

function round(n, decimals);

39

40

/**

41

* Calculate maximum value

42

* @param {...number} args - Numbers to compare

43

* @returns {number} Maximum value

44

*/

45

function max(...args);

46

47

/**

48

* Calculate minimum value

49

* @param {...number} args - Numbers to compare

50

* @returns {number} Minimum value

51

*/

52

function min(...args);

53

54

/**

55

* Constrain a value to a range

56

* @param {number} n - Value to constrain

57

* @param {number} low - Lower bound

58

* @param {number} high - Upper bound

59

* @returns {number} Constrained value

60

*/

61

function constrain(n, low, high);

62

63

/**

64

* Calculate distance between two points

65

* @param {number} x1 - X coordinate of first point

66

* @param {number} y1 - Y coordinate of first point

67

* @param {number} x2 - X coordinate of second point

68

* @param {number} y2 - Y coordinate of second point

69

* @returns {number} Distance between points

70

*/

71

function dist(x1, y1, x2, y2);

72

73

/**

74

* Calculate magnitude of a vector

75

* @param {number} a - X or first component

76

* @param {number} b - Y or second component

77

* @returns {number} Magnitude

78

*/

79

function mag(a, b);

80

81

/**

82

* Square a number

83

* @param {number} n - Input number

84

* @returns {number} Square of input

85

*/

86

function sq(n);

87

88

/**

89

* Calculate square root

90

* @param {number} n - Input number

91

* @returns {number} Square root

92

*/

93

function sqrt(n);

94

95

/**

96

* Calculate power (exponentiation)

97

* @param {number} n - Base number

98

* @param {number} e - Exponent

99

* @returns {number} n raised to power e

100

*/

101

function pow(n, e);

102

103

/**

104

* Calculate natural exponential

105

* @param {number} n - Input number

106

* @returns {number} e raised to power n

107

*/

108

function exp(n);

109

110

/**

111

* Calculate natural logarithm

112

* @param {number} n - Input number

113

* @returns {number} Natural log of n

114

*/

115

function log(n);

116

```

117

118

### Interpolation and Mapping

119

120

Functions for value interpolation and range mapping.

121

122

```javascript { .api }

123

/**

124

* Linear interpolation between two values

125

* @param {number} start - Start value

126

* @param {number} stop - End value

127

* @param {number} amt - Interpolation amount (0-1)

128

* @returns {number} Interpolated value

129

*/

130

function lerp(start, stop, amt);

131

132

/**

133

* Re-map a number from one range to another

134

* @param {number} value - Input value

135

* @param {number} start1 - Lower bound of input range

136

* @param {number} stop1 - Upper bound of input range

137

* @param {number} start2 - Lower bound of output range

138

* @param {number} stop2 - Upper bound of output range

139

* @param {boolean} [withinBounds] - Constrain result to output range

140

* @returns {number} Mapped value

141

*/

142

function map(value, start1, stop1, start2, stop2, withinBounds);

143

144

/**

145

* Normalize a value to 0-1 range

146

* @param {number} value - Input value

147

* @param {number} start - Lower bound of input range

148

* @param {number} stop - Upper bound of input range

149

* @returns {number} Normalized value (0-1)

150

*/

151

function norm(value, start, stop);

152

```

153

154

### Trigonometric Functions

155

156

Complete trigonometry functions with angle mode control.

157

158

```javascript { .api }

159

/**

160

* Calculate sine

161

* @param {number} angle - Angle in current angle mode

162

* @returns {number} Sine value

163

*/

164

function sin(angle);

165

166

/**

167

* Calculate cosine

168

* @param {number} angle - Angle in current angle mode

169

* @returns {number} Cosine value

170

*/

171

function cos(angle);

172

173

/**

174

* Calculate tangent

175

* @param {number} angle - Angle in current angle mode

176

* @returns {number} Tangent value

177

*/

178

function tan(angle);

179

180

/**

181

* Calculate arcsine

182

* @param {number} value - Input value (-1 to 1)

183

* @returns {number} Arcsine in current angle mode

184

*/

185

function asin(value);

186

187

/**

188

* Calculate arccosine

189

* @param {number} value - Input value (-1 to 1)

190

* @returns {number} Arccosine in current angle mode

191

*/

192

function acos(value);

193

194

/**

195

* Calculate arctangent

196

* @param {number} value - Input value

197

* @returns {number} Arctangent in current angle mode

198

*/

199

function atan(value);

200

201

/**

202

* Calculate two-argument arctangent

203

* @param {number} y - Y component

204

* @param {number} x - X component

205

* @returns {number} Angle from positive x-axis to point (x,y)

206

*/

207

function atan2(y, x);

208

209

/**

210

* Set the angle interpretation mode

211

* @param {string} mode - RADIANS or DEGREES

212

*/

213

function angleMode(mode);

214

215

/**

216

* Convert degrees to radians

217

* @param {number} degrees - Angle in degrees

218

* @returns {number} Angle in radians

219

*/

220

function radians(degrees);

221

222

/**

223

* Convert radians to degrees

224

* @param {number} radians - Angle in radians

225

* @returns {number} Angle in degrees

226

*/

227

function degrees(radians);

228

```

229

230

### Random Number Generation

231

232

Functions for generating random numbers and controlling randomness.

233

234

```javascript { .api }

235

/**

236

* Generate random number in range

237

* @param {number} [min] - Lower bound (or upper bound if max not specified)

238

* @param {number} [max] - Upper bound

239

* @returns {number} Random number

240

*/

241

function random(min, max);

242

243

/**

244

* Generate random number from Gaussian distribution

245

* @param {number} [mean=0] - Mean of distribution

246

* @param {number} [sd=1] - Standard deviation

247

* @returns {number} Random number from Gaussian distribution

248

*/

249

function randomGaussian(mean, sd);

250

251

/**

252

* Set the seed for random number generation

253

* @param {number} seed - Seed value

254

*/

255

function randomSeed(seed);

256

```

257

258

### Noise Functions

259

260

Perlin noise functions for smooth, natural-looking randomness.

261

262

```javascript { .api }

263

/**

264

* Generate Perlin noise value

265

* @param {number} x - X coordinate in noise space

266

* @param {number} [y] - Y coordinate in noise space

267

* @param {number} [z] - Z coordinate in noise space

268

* @returns {number} Noise value (0-1)

269

*/

270

function noise(x, y, z);

271

272

/**

273

* Set the detail level of noise

274

* @param {number} lod - Level of detail (octaves)

275

* @param {number} falloff - Falloff for each octave

276

*/

277

function noiseDetail(lod, falloff);

278

279

/**

280

* Set the seed for noise generation

281

* @param {number} seed - Seed value

282

*/

283

function noiseSeed(seed);

284

```

285

286

### p5.Vector Class

287

288

Comprehensive 2D/3D vector class for position, velocity, and acceleration calculations.

289

290

```javascript { .api }

291

/**

292

* 2D/3D vector class

293

*/

294

class p5.Vector {

295

/**

296

* Create a new vector

297

* @param {number} [x=0] - X component

298

* @param {number} [y=0] - Y component

299

* @param {number} [z=0] - Z component

300

*/

301

constructor(x, y, z);

302

303

/** X component */

304

x;

305

/** Y component */

306

y;

307

/** Z component */

308

z;

309

310

/**

311

* Set vector components

312

* @param {number|p5.Vector} [x] - X component or vector to copy

313

* @param {number} [y] - Y component

314

* @param {number} [z] - Z component

315

* @returns {p5.Vector} This vector for chaining

316

*/

317

set(x, y, z);

318

319

/**

320

* Create a copy of this vector

321

* @returns {p5.Vector} New vector copy

322

*/

323

copy();

324

325

/**

326

* Add to this vector

327

* @param {number|p5.Vector} x - X component or vector to add

328

* @param {number} [y] - Y component

329

* @param {number} [z] - Z component

330

* @returns {p5.Vector} This vector for chaining

331

*/

332

add(x, y, z);

333

334

/**

335

* Subtract from this vector

336

* @param {number|p5.Vector} x - X component or vector to subtract

337

* @param {number} [y] - Y component

338

* @param {number} [z] - Z component

339

* @returns {p5.Vector} This vector for chaining

340

*/

341

sub(x, y, z);

342

343

/**

344

* Multiply vector by scalar

345

* @param {number} scalar - Multiplier

346

* @returns {p5.Vector} This vector for chaining

347

*/

348

mult(scalar);

349

350

/**

351

* Divide vector by scalar

352

* @param {number} scalar - Divisor

353

* @returns {p5.Vector} This vector for chaining

354

*/

355

div(scalar);

356

357

/**

358

* Modulo operation on vector components

359

* @param {number|p5.Vector} x - X divisor or vector

360

* @param {number} [y] - Y divisor

361

* @param {number} [z] - Z divisor

362

* @returns {p5.Vector} This vector for chaining

363

*/

364

rem(x, y, z);

365

366

/**

367

* Calculate magnitude (length) of vector

368

* @returns {number} Magnitude

369

*/

370

mag();

371

372

/**

373

* Calculate magnitude squared (faster than mag())

374

* @returns {number} Magnitude squared

375

*/

376

magSq();

377

378

/**

379

* Calculate dot product with another vector

380

* @param {p5.Vector} v - Other vector

381

* @returns {number} Dot product

382

*/

383

dot(v);

384

385

/**

386

* Calculate cross product with another vector

387

* @param {p5.Vector} v - Other vector

388

* @returns {p5.Vector} Cross product vector

389

*/

390

cross(v);

391

392

/**

393

* Calculate distance to another vector

394

* @param {p5.Vector} v - Other vector

395

* @returns {number} Distance

396

*/

397

dist(v);

398

399

/**

400

* Normalize vector to unit length (magnitude 1)

401

* @returns {p5.Vector} This vector for chaining

402

*/

403

normalize();

404

405

/**

406

* Limit magnitude to maximum value

407

* @param {number} max - Maximum magnitude

408

* @returns {p5.Vector} This vector for chaining

409

*/

410

limit(max);

411

412

/**

413

* Set magnitude to specific value

414

* @param {number} n - New magnitude

415

* @returns {p5.Vector} This vector for chaining

416

*/

417

setMag(n);

418

419

/**

420

* Calculate 2D heading angle

421

* @returns {number} Angle in radians

422

*/

423

heading();

424

425

/**

426

* Set 2D heading angle

427

* @param {number} angle - Angle in radians

428

* @returns {p5.Vector} This vector for chaining

429

*/

430

setHeading(angle);

431

432

/**

433

* Rotate vector by angle

434

* @param {number} angle - Rotation angle in radians

435

* @returns {p5.Vector} This vector for chaining

436

*/

437

rotate(angle);

438

439

/**

440

* Calculate angle between this and another vector

441

* @param {p5.Vector} v - Other vector

442

* @returns {number} Angle in radians

443

*/

444

angleBetween(v);

445

446

/**

447

* Linear interpolation toward another vector

448

* @param {p5.Vector} v - Target vector

449

* @param {number} amt - Interpolation amount (0-1)

450

* @returns {p5.Vector} This vector for chaining

451

*/

452

lerp(v, amt);

453

454

/**

455

* Spherical linear interpolation toward another vector

456

* @param {p5.Vector} v - Target vector

457

* @param {number} amt - Interpolation amount (0-1)

458

* @returns {p5.Vector} This vector for chaining

459

*/

460

slerp(v, amt);

461

462

/**

463

* Reflect vector off surface with given normal

464

* @param {p5.Vector} normal - Surface normal vector

465

* @returns {p5.Vector} This vector for chaining

466

*/

467

reflect(normal);

468

469

/**

470

* Convert vector to array

471

* @returns {number[]} Array of [x, y, z] components

472

*/

473

array();

474

475

/**

476

* Test equality with another vector

477

* @param {p5.Vector} v - Other vector

478

* @returns {boolean} True if vectors are equal

479

*/

480

equals(v);

481

482

/**

483

* String representation

484

* @returns {string} String format: "x: 1, y: 2, z: 3"

485

*/

486

toString();

487

488

// Static methods

489

/**

490

* Create vector from angle and length

491

* @param {number} angle - Angle in radians

492

* @param {number} [length=1] - Vector length

493

* @returns {p5.Vector} New vector

494

*/

495

static fromAngle(angle, length);

496

497

/**

498

* Create 3D vector from spherical angles

499

* @param {number} theta - Azimuthal angle

500

* @param {number} phi - Polar angle

501

* @param {number} [length=1] - Vector length

502

* @returns {p5.Vector} New vector

503

*/

504

static fromAngles(theta, phi, length);

505

506

/**

507

* Create random 2D unit vector

508

* @returns {p5.Vector} Random 2D unit vector

509

*/

510

static random2D();

511

512

/**

513

* Create random 3D unit vector

514

* @returns {p5.Vector} Random 3D unit vector

515

*/

516

static random3D();

517

518

// All instance methods are also available as static methods

519

// that take vectors as arguments and return new vectors

520

}

521

```

522

523

## Constants

524

525

```javascript { .api }

526

// Mathematical constants

527

const PI = Math.PI;

528

const HALF_PI = Math.PI / 2;

529

const QUARTER_PI = Math.PI / 4;

530

const TWO_PI = Math.PI * 2;

531

const TAU = Math.PI * 2;

532

533

// Angle mode constants

534

const RADIANS = 'radians';

535

const DEGREES = 'degrees';

536

```

537

538

## Usage Examples

539

540

**Basic Math Operations:**

541

```javascript

542

function setup() {

543

createCanvas(400, 300);

544

545

let values = [12.7, 8.3, 15.9, 4.1, 11.2];

546

547

let sum = values.reduce((a, b) => a + b);

548

let average = sum / values.length;

549

let maxVal = max(...values);

550

let minVal = min(...values);

551

552

console.log(`Sum: ${sum}`);

553

console.log(`Average: ${average.toFixed(2)}`);

554

console.log(`Max: ${maxVal}, Min: ${minVal}`);

555

console.log(`Distance from origin to (3,4): ${dist(0, 0, 3, 4)}`);

556

}

557

```

558

559

**Value Mapping and Interpolation:**

560

```javascript

561

function draw() {

562

background(220);

563

564

// Map mouse position to circle size

565

let size = map(mouseX, 0, width, 20, 200);

566

567

// Map mouse Y to color

568

let grayValue = map(mouseY, 0, height, 0, 255);

569

570

fill(grayValue);

571

circle(width/2, height/2, size);

572

573

// Lerp between two positions

574

let targetX = mouseX;

575

let currentX = lerp(width/4, targetX, 0.05);

576

577

fill('red');

578

circle(currentX, height/4, 30);

579

}

580

```

581

582

**Trigonometry Example:**

583

```javascript

584

function draw() {

585

background(220);

586

translate(width/2, height/2);

587

588

// Create a sine wave

589

stroke('blue');

590

strokeWeight(2);

591

noFill();

592

593

beginShape();

594

for (let x = -width/2; x < width/2; x += 5) {

595

let angle = map(x, -width/2, width/2, 0, TWO_PI * 2);

596

let y = sin(angle + frameCount * 0.02) * 50;

597

vertex(x, y);

598

}

599

endShape();

600

601

// Rotating line using cos and sin

602

let angle = frameCount * 0.02;

603

let x = cos(angle) * 80;

604

let y = sin(angle) * 80;

605

606

stroke('red');

607

strokeWeight(3);

608

line(0, 0, x, y);

609

}

610

```

611

612

**Vector Physics Simulation:**

613

```javascript

614

let position, velocity, acceleration;

615

616

function setup() {

617

createCanvas(400, 300);

618

619

position = createVector(width/2, height/2);

620

velocity = createVector(0, 0);

621

acceleration = createVector(0, 0);

622

}

623

624

function draw() {

625

background(220);

626

627

// Calculate acceleration toward mouse

628

let mouse = createVector(mouseX, mouseY);

629

acceleration = p5.Vector.sub(mouse, position);

630

acceleration.normalize();

631

acceleration.mult(0.2);

632

633

// Update physics

634

velocity.add(acceleration);

635

velocity.limit(5); // Limit max speed

636

position.add(velocity);

637

638

// Bounce off edges

639

if (position.x < 0 || position.x > width) velocity.x *= -1;

640

if (position.y < 0 || position.y > height) velocity.y *= -1;

641

642

// Keep position in bounds

643

position.x = constrain(position.x, 0, width);

644

position.y = constrain(position.y, 0, height);

645

646

// Draw

647

fill('red');

648

circle(position.x, position.y, 30);

649

650

// Show velocity vector

651

stroke('blue');

652

let vel = p5.Vector.mult(velocity, 10);

653

line(position.x, position.y, position.x + vel.x, position.y + vel.y);

654

}

655

```

656

657

**Noise-based Animation:**

658

```javascript

659

let noiseOffset = 0;

660

661

function draw() {

662

background(220);

663

664

// Create organic movement using noise

665

for (let x = 0; x < width; x += 20) {

666

for (let y = 0; y < height; y += 20) {

667

let noiseValue = noise(x * 0.01, y * 0.01, noiseOffset);

668

let size = map(noiseValue, 0, 1, 5, 25);

669

let gray = map(noiseValue, 0, 1, 100, 255);

670

671

fill(gray);

672

circle(x, y, size);

673

}

674

}

675

676

noiseOffset += 0.01;

677

}

678

```

679

680

**Vector Field Visualization:**

681

```javascript

682

function draw() {

683

background(240);

684

685

// Draw vector field

686

for (let x = 20; x < width; x += 30) {

687

for (let y = 20; y < height; y += 30) {

688

// Create vector based on position

689

let angle = atan2(y - height/2, x - width/2);

690

let magnitude = map(dist(x, y, width/2, height/2), 0, 200, 0, 20);

691

692

let vector = p5.Vector.fromAngle(angle, magnitude);

693

694

// Draw vector as line

695

stroke(0, 100);

696

strokeWeight(1);

697

line(x, y, x + vector.x, y + vector.y);

698

699

// Draw arrowhead

700

push();

701

translate(x + vector.x, y + vector.y);

702

rotate(vector.heading());

703

stroke(0, 150);

704

line(0, 0, -5, -2);

705

line(0, 0, -5, 2);

706

pop();

707

}

708

}

709

}

710

```