...loading...
SWPoint Class Reference
Overview
The SWPoint class represents points or vectors in 2D or 3D space with styling options. It is designed to work seamlessly within the p5.js environment and integrates with the SketchWave ecosystem, particularly the SWColor and SWGrid classes.
Key Features:
- Support for 2D and 3D coordinates
- Customizable stroke weight and color
- Pen trail functionality to track point movement
- Drawing in both screen and user (grid) coordinates
- Vector operations (distance calculations)
- Extensible design for animation and interaction
Constructor
new SWPoint(x, y, z, strokeWeight, strokeColor)
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
x |
number | required | X coordinate of the point |
y |
number | required | Y coordinate of the point |
z |
number | undefined | Z coordinate (optional, for 3D space) |
strokeWeight |
number | 1 | Weight/thickness of the point when drawn |
strokeColor |
SWColor | undefined | An SWColor instance for the point's color |
Example:
// Create a simple 2D point
let point1 = new SWPoint(100, 200);
// Create a styled 2D point
let redColor = new SWColor(255, 0, 0);
let point2 = new SWPoint(150, 250, undefined, 5, redColor);
// Create a 3D point
let blueColor = new SWColor(0, 0, 255);
let point3 = new SWPoint(100, 150, 50, 3, blueColor);
Properties
| Property | Type | Description |
|---|---|---|
x |
number | X coordinate of the point |
y |
number | Y coordinate of the point |
z |
number | undefined | Z coordinate (undefined for 2D points) |
strokeWeight |
number | The weight/thickness when drawing the point |
strokeColor |
SWColor | The SWColor instance for the point's color |
penOn |
boolean | Whether the pen trail is active (default: false) |
trail |
Array | Array of previous positions [{x, y, z}] |
maxTrailLength |
number | Maximum number of trail points (default: 500) |
x, y, or z, call _updateTrail() or use the move() method to ensure the trail is updated properly if the pen is on.
Methods
Drawing Methods
draw()
Draws the point using p5.js in screen coordinates.
function draw() {
background(220);
myPoint.draw();
}
drawOnGrid(grid)
Draws the point using user (grid) coordinates mapped by the given SWGrid instance.
Parameters:grid(SWGrid): The grid instance for coordinate transformation
let myGrid = new SWGrid(-10, 10, -10, 10);
myPoint.drawOnGrid(myGrid);
drawTrail()
Draws the pen trail in screen coordinates. Only draws if pen is on and trail has at least 2 points.
myPoint.setPen(true);
// ... move the point around ...
myPoint.drawTrail(); // Shows the path
drawTrailOnGrid(grid)
Draws the pen trail in user (grid) coordinates.
Parameters:grid(SWGrid): The grid instance for coordinate transformation
Movement Methods
move(dx, dy, dz)
Moves the point by the specified deltas. Automatically updates the trail if pen is on.
Parameters:dx(number): Change in x coordinatedy(number): Change in y coordinatedz(number): Change in z coordinate (default: 0)
// Move point right by 10 and up by 5
myPoint.move(10, -5);
// Animate movement
function draw() {
background(220);
myPoint.move(1, sin(frameCount * 0.05) * 2);
myPoint.drawTrail();
myPoint.draw();
}
Pen Trail Methods
setPen(on)
Enables or disables the pen trail. When disabled, clears the trail.
Parameters:on(boolean): true to enable, false to disable (default: true)
myPoint.setPen(true); // Start recording trail
myPoint.setPen(false); // Stop and clear trail
setMaxTrailLength(n)
Sets the maximum number of points in the trail. Older points are removed when limit is exceeded.
Parameters:n(number): Maximum trail length
myPoint.setMaxTrailLength(100); // Keep last 100 positions
clearTrail()
Clears the trail history without changing the pen state.
myPoint.clearTrail(); // Remove all trail points
Style Methods
setStrokeColor(swColor)
Sets the stroke color using an SWColor instance.
Parameters:swColor(SWColor): The new color
let newColor = new SWColor(0, 255, 0);
myPoint.setStrokeColor(newColor);
setStrokeWeight(w)
Sets the stroke weight (thickness).
Parameters:w(number): The new stroke weight
myPoint.setStrokeWeight(8);
Utility Methods
distanceTo(otherSWPt)
Returns the Euclidean distance to another SWPoint in user coordinates.
Parameters:otherSWPt(SWPoint): The other point
let point1 = new SWPoint(0, 0);
let point2 = new SWPoint(3, 4);
let distance = point1.distanceTo(point2); // Returns 5
toString()
Returns a string representation of the point, useful for debugging.
console.log(myPoint.toString());
// Output: "SWPoint(x: 100, y: 200, strokeWeight: 1, strokeColor: ..., penOn: false, trailLen: 0)"
Usage Examples
Example 1: Basic Point Drawing
let myPoint;
function setup() {
createCanvas(400, 400);
let red = new SWColor(255, 0, 0);
myPoint = new SWPoint(200, 200, undefined, 10, red);
}
function draw() {
background(220);
myPoint.draw();
}
Example 2: Animated Point with Trail
let myPoint;
let angle = 0;
function setup() {
createCanvas(400, 400);
let blue = new SWColor(0, 100, 255);
myPoint = new SWPoint(200, 200, undefined, 5, blue);
myPoint.setPen(true);
myPoint.setMaxTrailLength(200);
}
function draw() {
background(220);
// Circular motion
let radius = 100;
let dx = cos(angle) * radius - myPoint.x + width/2;
let dy = sin(angle) * radius - myPoint.y + height/2;
myPoint.move(dx * 0.1, dy * 0.1);
angle += 0.05;
myPoint.drawTrail();
myPoint.draw();
}
Example 3: Using with SWGrid
let myGrid;
let myPoint;
function setup() {
createCanvas(400, 400);
myGrid = new SWGrid(-10, 10, -10, 10);
let green = new SWColor(0, 200, 0);
// Point at user coordinates (5, 3)
myPoint = new SWPoint(5, 3, undefined, 8, green);
}
function draw() {
background(220);
myGrid.draw();
myPoint.drawOnGrid(myGrid);
}
Example 4: Interactive Point
let myPoint;
function setup() {
createCanvas(400, 400);
let purple = new SWColor(150, 0, 200);
myPoint = new SWPoint(mouseX, mouseY, undefined, 6, purple);
myPoint.setPen(true);
}
function draw() {
background(220, 10); // Fade effect
// Follow mouse
myPoint.x = mouseX;
myPoint.y = mouseY;
myPoint._updateTrail(); // Update trail manually
myPoint.drawTrail();
myPoint.draw();
}
function mousePressed() {
myPoint.clearTrail(); // Clear trail on click
}
Extending SWPoint
The SWPoint class is designed to be extended for more specialized behavior. Here are some examples:
Example: Animated Point Class
class AnimatedPoint extends SWPoint {
constructor(x, y, strokeWeight, strokeColor) {
super(x, y, undefined, strokeWeight, strokeColor);
this.velocity = {x: random(-2, 2), y: random(-2, 2)};
this.acceleration = {x: 0, y: 0};
}
update() {
this.velocity.x += this.acceleration.x;
this.velocity.y += this.acceleration.y;
this.move(this.velocity.x, this.velocity.y);
// Bounce off edges
if (this.x < 0 || this.x > width) this.velocity.x *= -1;
if (this.y < 0 || this.y > height) this.velocity.y *= -1;
}
applyForce(fx, fy) {
this.acceleration.x = fx;
this.acceleration.y = fy;
}
}
Example: Particle System Using SWPoint
class Particle extends SWPoint {
constructor(x, y) {
let randomColor = new SWColor(random(255), random(255), random(255));
super(x, y, undefined, random(2, 8), randomColor);
this.setPen(true);
this.setMaxTrailLength(50);
this.lifespan = 255;
}
update() {
this.move(random(-2, 2), random(-2, 2));
this.lifespan -= 2;
}
isDead() {
return this.lifespan <= 0;
}
display() {
this.strokeColor.setAlpha(this.lifespan);
this.drawTrail();
this.draw();
}
}
Integration with SketchWave Ecosystem
Dependencies
- p5.js: Required for all drawing operations
- SWColor: Required for color management
- SWGrid: Optional, for grid-based coordinate systems
Loading Order
Ensure scripts are loaded in this order in your HTML:
<!-- p5js CDN-->
<script src="https://cdn.jsdelivr.net/npm/p5@1.6.0/lib/p5.js"></script>
<!-- SketchWave classes -->
<script src="scripts/swColor.js"></script>
<script src="scripts/swPoint.js"></script>
<script src="scripts/swGrid.js"></script>
<!-- Your sketch script -->
<script src="scripts/mySketch.js"></script>
Best Practices
- Always use
SWColorinstances for colors rather than raw p5.js colors - Use
move()method rather than directly modifying x/y if pen trail is active - Limit
maxTrailLengthfor performance in animations with many points - Clear trails periodically in long-running animations to prevent memory buildup
- When working with grids, use
drawOnGrid()for proper coordinate transformation
Complete Source Code
View the complete, documented source code for the SWPoint class:
Show/Hide Source Code
/*
File: swPoint.js
Date: 2026-01-30
Author: klp
Workspace: SWaveJS2026-01-30-StgC
Purpose: SWPoint class for SketchWaveJS
Comment(s):
TODO:
=== Notes ===:
- This class assumes p5.js and SWColor are loaded in the environment.
- SWPoint class represents points or vectors in 2D or 3D space with styling options.
- Includes properties for position (x, y, z), stroke weight, and stroke color.
- Supports pen trail functionality to track and draw the path of the point.
- Designed to be compatible with p5.js and the SWColor class.
- Methods for drawing the point and its trail in screen coordinates.
- Additional methods for movement and vector math can be added as needed.
- For heavy math, consider extending or wrapping p5.Vector.
- strokeColor should be an SWColor instance for consistency.
- Optionally, you can add fillColor or other style properties.
- Pen trail logic includes enabling/disabling the pen, storing trail points, and limiting trail length.
- You can extend this class for animated or interactive points.
*/
console.log("[swPoint.js] SWPoint class loaded.");
class SWPoint {
/**
* @param {number} x - X coordinate
* @param {number} y - Y coordinate
* @param {number} [z] - Z coordinate (optional, for 3D)
* @param {number} [strokeWeight=1] - Stroke weight
* @param {SWColor} [strokeColor] - Stroke color (SWColor instance)
*/
constructor(x, y, z = undefined, strokeWeight = 1, strokeColor = undefined) {
this.x = x;
this.y = y;
this.z = z;
this.strokeWeight = strokeWeight;
this.strokeColor = strokeColor; // Always store SWColor instance
// Pen trail logic
this.penOn = false;
this.trail = [];
this.maxTrailLength = 500; // default, can be changed
}//end constructor
/**
* Draws the point using p5.js in screen coordinates
*/
draw() {
if (this.strokeColor && this.strokeColor.col) {
stroke(this.strokeColor.col);
}
strokeWeight(this.strokeWeight);
if (this.z !== undefined) {
point(this.x, this.y, this.z);
} else {
point(this.x, this.y);
}
noStroke();
strokeWeight(1);
}//end draw
/**
* Draws the point using user (grid) coordinates mapped by the given SWGrid
* @param {SWGrid} grid
*/
drawOnGrid(grid) {
const {x: px, y: py} = grid.userToScreen(this.x, this.y);
if (this.strokeColor && this.strokeColor.col) {
stroke(this.strokeColor.col);
}
strokeWeight(this.strokeWeight);
if (this.z !== undefined) {
point(px, py, this.z);
} else {
point(px, py);
}
noStroke();
strokeWeight(1);
}//end drawOnGrid
/**
* Pen trail enhancements:
* - penOn: whether the pen is active
* - trail: array of previous positions [{x, y, z}]
* - maxTrailLength: maximum number of points in the trail
*/
/**
* Draws the pen trail in screen coordinates
*/
drawTrail() {
if (!this.penOn || this.trail.length < 2) return;
noFill();
stroke(this.strokeColor && this.strokeColor.col ? this.strokeColor.col : 0);
strokeWeight(Math.max(1, this.strokeWeight / 2));
beginShape();
for (const pt of this.trail) {
if (this.z !== undefined && pt.z !== undefined) {
vertex(pt.x, pt.y, pt.z);
} else {
vertex(pt.x, pt.y);
}
}
endShape();
noStroke();
strokeWeight(1);
}//end drawTrail
/**
* Draws the pen trail in user (grid) coordinates
* @param {SWGrid} grid
*/
drawTrailOnGrid(grid) {
if (!this.penOn || this.trail.length < 2) return;
noFill();
stroke(this.strokeColor && this.strokeColor.col ? this.strokeColor.col : 0);
strokeWeight(Math.max(1, this.strokeWeight / 2));
beginShape();
for (const pt of this.trail) {
const {x, y} = grid.userToScreen(pt.x, pt.y);
vertex(x, y);
}
endShape();
noStroke();
strokeWeight(1);
}//end drawTrailOnGrid
/**
* Moves the point by dx, dy, dz
* If pen is on, records the new position in the trail
*/
move(dx, dy, dz = 0) {
this.x += dx;
this.y += dy;
if (this.z !== undefined) this.z += dz;
this._updateTrail();
}//end move
/**
* Call this after manually setting x/y/z to update the trail if pen is on
* Private method: do not call directly (as indicated by underscore prefix)
*/
_updateTrail() {
if (this.penOn) {
// Only add if position changed
if (
this.trail.length === 0 ||
this.trail[this.trail.length - 1].x !== this.x ||
this.trail[this.trail.length - 1].y !== this.y ||
this.trail[this.trail.length - 1].z !== this.z
) {
this.trail.push({ x: this.x, y: this.y, z: this.z });
if (this.trail.length > this.maxTrailLength) {
this.trail.shift();
}
}
}
}//end _updateTrail
/**
* Enable or disable the pen trail
* @param {boolean} on
*/
setPen(on = true) {
this.penOn = on;
if (!on) this.trail = [];
}//end setPen
/**
* Set the maximum trail length
* @param {number} n
*/
setMaxTrailLength(n) {
this.maxTrailLength = n;
if (this.trail.length > n) {
this.trail = this.trail.slice(-n);
}
}//end setMaxTrailLength
/**
* Clears the pen trail history, regardless of pen state
*/
clearTrail() {
this.trail = [];
}//end clearTrail
/**
* Sets the stroke color
* @param {SWColor} swColor
*/
setStrokeColor(swColor) {
this.strokeColor = swColor;
}//end setStrokeColor
/**
* Sets the stroke weight
* @param {number} w
*/
setStrokeWeight(w) {
this.strokeWeight = w;
}//end setStrokeWeight
/**
* Returns a string representation
*/
toString() {
return `SWPoint(x: ${this.x}, y: ${this.y}` +
(this.z !== undefined ? `, z: ${this.z}` : '') +
`, strokeWeight: ${this.strokeWeight}, strokeColor: ${this.strokeColor ? this.strokeColor.toString() : 'none'}, penOn: ${this.penOn}, trailLen: ${this.trail.length})`;
}//end toString
/**
* Returns the Euclidean distance to another SWPoint in user coordinates
* @param {SWPoint} otherSWPt
* @returns {number}
*/
distanceTo(otherSWPt) {
const dx = this.x - otherSWPt.x;
const dy = this.y - otherSWPt.y;
// If both have z, use 3D distance; otherwise, 2D
if (this.z !== undefined && otherSWPt.z !== undefined) {
const dz = this.z - otherSWPt.z;
return Math.sqrt(dx * dx + dy * dy + dz * dz);
} else {
return Math.sqrt(dx * dx + dy * dy);
}
}//end distanceTo
}//end SWPoint class