Drawing and Styling Line Segments in p5.js
Linee segment are among the simplest graphical primitives—ideal for outlining shapes, connecting points, or constructing compound visuals. In p5.js, the line() function provides an intuitive way to render straight segments between two coordinates, abstracting away low-level canvas complexities.
Syntax and Parameters
The 2D version of line() accepts exactly four numeric arguments:
line(startX, startY, endX, endY);
startX,startY: Coordinates of the segment’s origin.endX,endY: Coordinates of its terminus.
For example, line(60, 40, 220, 130) draws a segment from (60, 40) to (220, 130).
Styling Lines
Lines have no interior area, so fill() has no effect. Appearance is controlled exclusively via:
stroke(color): Sets the line’s color using RGB values, named colors ('red'), or hex strings ('#ff5733').strokeWeight(weight): Specifies line thickness in pixels; default is1.
Note: stroke() and strokeWeight() affect all subsequent lines until redefined.
Basic Example
function setup() {
createCanvas(400, 300);
background(240);
}
function draw() {
line(60, 60, 340, 240);
}
This renders a default black, 1-pixel-thick diagonal segment on a light-gray background.
Customized Parallel Segments
function setup() {
createCanvas(400, 300);
background(240);
noLoop();
}
function draw() {
// Thick red horizontal segment
stroke(255, 0, 0);
strokeWeight(6);
line(60, 90, 340, 90);
// Medium blue horizontal segment
stroke(0, 0, 255);
strokeWeight(4);
line(60, 150, 340, 150);
// Thin green horizontal segment
stroke(0, 255, 0);
strokeWeight(2);
line(60, 210, 340, 210);
}
All three segments share identical y-values to their endpoints, ensuring perfect horizontality.
Constructing Shapes with Segments
Complex outlines emerge from chaining segments. Here’s how to build a triangle and a rectangle manually:
function setup() {
createCanvas(400, 300);
background(255);
noLoop();
stroke(0);
strokeWeight(2);
}
function draw() {
// Triangle: three connected edges
line(110, 110, 190, 210);
line(190, 210, 30, 210);
line(30, 210, 110, 110);
// Rectangle: four orthogonal edges
line(230, 110, 360, 110);
line(360, 110, 360, 210);
line(360, 210, 230, 210);
line(230, 210, 230, 110);
}
Each shape consists solely of line segments—no built-in triangle() or rect() calls involved.
Interactive Line Following the Cursor
Dynamic behavior arises naturally from p5.js’s frame loop and mouse state variables:
function setup() {
createCanvas(400, 300);
}
function draw() {
background(240);
stroke(139, 69, 19);
strokeWeight(3);
line(200, 150, mouseX, mouseY);
}
Here, one endpoint remains fixed at the canvas center while the other tracks real-time mouse position. Repeated background() calls erase prior frames, yielding smooth motion without trailing artifacts.