shape|p5_color|p5_math|p5_transform|p5_event|p5_image|p5_typography|p5_io 🌱 Beginner

line()

The line() function in p5.js draws a straight line between two specified points on the canvas. This is essential for creating shapes, patterns, and connections in your visuals, allowing a creative coder to explore geometric designs, data visualization, and artistic expressions. For instance, you might use line() to create a network of connections in an interactive data display, helping viewers visually grasp relationships between different elements.

📖 p5.js Reference →

🧠 See The Whole Picture

Visualize the canvas as a grid where each intersection has coordinates, like a chessboard. The line() function takes the coordinates you provide and connects those points with a straight path. Imagine drawing a tightrope between two points, where the endpoints are fixed, and the line represents the tightrope connecting them.

📖 Visual Learner's Guide

The Big Picture:

If you run this code, you'd see a diagonal line stretching across the canvas.

Visual Analogy:

Imagine a piece of string that you pull tight between two points marked on a wall. The line() function does just that - it connects two points on your canvas with a straight line.

The Numbers Decoded:

Here, x1=100 means 100 pixels from the left edge, y1=100 means 100 pixels from the top edge. The line starts there. x2=300 means it ends 300 pixels from the left, and y2=300 means it ends 300 pixels down from the top.

Connection Map:

Before drawing the line, using stroke() can set the color of the line, and after drawing, you could use noStroke() to make future shapes invisible.

Common Gotcha:

Remember, the coordinates are absolute positions on the canvas, so ensure they are within the canvas size to avoid unexpected results.

🔄 How It Works

This diagram illustrates the flow from your code to the line being drawn on the canvas. The code calls the line function, which then renders the line visually on the canvas.

📝 Syntax

📖 How to Read This

Read line(x1, y1, x2, y2) as: Draw a line FROM the position (x1, y1) TO the position (x2, y2). The parentheses act like a delivery box, providing the function with the start and endpoints it needs to draw.

line(x1, y1, x2, y2)

Example: line(200, 150, 80, 300)

🔀 Different Ways to Call It

line(value)

This form is used for drawing a single line segment. However, this signature is not typically valid as it requires four parameters. Instead, it serves as a reminder that every line requires two endpoints.

line(128, 128, 256, 256) → A diagonal line drawn from point (128, 128) to (256, 256) on the canvas.
line(v1, v2, v3, v4)

This form is used to specify the start and end points of the line. v1 and v2 are the coordinates of the start point, and v3 and v4 are the coordinates of the end point.

line(255, 100, 50, 200) → A line drawn from the point (255, 100) to the point (50, 200) on the canvas.

â†Šī¸ What It Returns

Type: void

The line() function does not return any value; it directly draws on the canvas, similar to asking someone to draw a line on a piece of paper without expecting anything back.

đŸ“Ĩ What Goes In

You give line() four numbers. The first two are like GPS coordinates that tell WHERE to place the start of the line. The next two are for the endpoint, guiding where the line will end. Each coordinate narrows down the precise location on the canvas, just like a map pinpointing a destination.

📤 What Happens

When line() receives your instructions, it draws a line directly on the canvas from the starting point to the endpoint. It uses whatever stroke color you have set (imagine dipping a brush in paint) to outline the line, making it visible against the background.

Parameters

x1 Number required

A Number represents a specific pixel location on the canvas, such as coordinates on a graph.

This parameter controls the x-coordinate of the starting point of the line. Typical values range from 0 to the width of the canvas. At 0, the line starts at the left edge; at the maximum value, it starts at the right edge.

Range: 0 to canvas width

Examples: 0 → A line starting from the very left edge of the canvas. 200 → A line starting horizontally centered in the canvas. 400 → A line starting from the very right edge of the canvas.
y1 Number required

A Number represents a specific pixel location on the canvas, indicating vertical positioning.

This parameter controls the y-coordinate of the starting point of the line. Typical values range from 0 (top) to canvas height (bottom). At 0, the line starts at the top; at the maximum value, it starts at the bottom.

Range: 0 to canvas height

Examples: 0 → A line starting from the very top edge of the canvas. 200 → A line starting horizontally centered in the canvas. 400 → A line starting from the very bottom edge of the canvas.
x2 Number required

A Number represents a specific pixel location on the canvas, indicating the end of the line.

This parameter controls the x-coordinate of the endpoint of the line. Values range from 0 to the width of the canvas. At 0, the line ends at the left edge; at the maximum value, it ends at the right edge.

Range: 0 to canvas width

Examples: 0 → A line ending at the left edge of the canvas. 200 → A line ending horizontally centered in the canvas. 400 → A line ending at the right edge of the canvas.
y2 Number required

A Number represents a specific pixel location on the canvas, indicating the vertical end of the line.

This parameter controls the y-coordinate of the endpoint of the line. Values range from 0 (top) to canvas height (bottom). At 0, the line ends at the top; at the maximum value, it ends at the bottom.

Range: 0 to canvas height

Examples: 0 → A line ending at the top edge of the canvas. 200 → A line ending horizontally centered in the canvas. 400 → A line ending at the bottom edge of the canvas.

💡 How Parameters Work Together

Think of the parameters as the corners of a rectangle that define the line's path. The first two numbers dictate where the line starts, and the last two determine where it ends. You might visualize it as stretching a string between two fixed points - the string will only span the distance defined by your coordinates.

đŸ’ģ Working Example

// Complete working example with comments
function setup() {
  createCanvas(400, 400); // Create a canvas of 400x400 pixels
}

function draw() {
  background(220); // Set a light gray background
  line(100, 100, 300, 300); // Draw a line from (100, 100) to (300, 300)
}
Try This Code →

âš™ī¸ How It Works

When you call the line() function, p5.js processes the four parameters you provide, determining where to start and end the line. It then updates the canvas's pixel data, rendering the line in the stroke color currently set. This operation occurs within the draw loop, allowing for real-time changes if the parameters are dynamic.

🎓 Learn Prompt Patterns

These patterns help you write better prompts for ANY function:

🎭 Persona Pattern

Tell the AI to act as a specific type of creator.

"Act as a creative coder making generative art. Use line() to create a radiant sunburst effect."

Why it works: Giving the AI a persona helps it understand the CONTEXT and style you want.

📋 Recipe Pattern

Ask for step-by-step instructions.

"Give me step-by-step code to use line() to create a star shape."

Why it works: Breaking down into steps helps you understand each part and learn incrementally.

📝 Template Pattern

Provide a structure for the AI to fill in.

"Use this template: setup creates canvas, draw uses line() with specified parameters to make a simple pyramid."

Why it works: Templates give the AI clear constraints, resulting in more predictable output.

🔄 Refinement Pattern

Start simple and iterate.

"Start with a basic line() example. Then I'll ask you to add color, animation, and interaction."

Why it works: Building up gradually helps you understand each addition and not get overwhelmed.

đŸŽ¯ Direct Prompts - Name the Function

Tell the AI exactly which function to use:

Direct

"Create a series of lines that form a spider web using line()."

💡 Why this is good: This prompt directs the AI to focus on a specific visual outcome while using the line function effectively.

📚 What you learn: You learn to create complex visuals using multiple simple functions.

📝 Sample Output:
// Code for drawing a spider web
Direct

"Generate a dynamic grid pattern with line() that changes with mouse movement."

💡 Why this is good: This promotes interaction and learning about dynamic visuals.

📚 What you learn: You learn to integrate interaction with visuals.

📝 Sample Output:
// Code for dynamic grid pattern

🔮 Indirect Prompts - Describe What You Want

Don't name the function - see if the AI figures out to use line():

Indirect

"Describe a visual of connecting points with straight lines."

💡 Why this is good: This encourages you to express visual ideas without focusing on specific function names.

īŋŊ What you learn: You learn to communicate visual intent, not just function names.

📝 Sample Output:
// Code showing AI chose line() to connect points

đŸ–ŧī¸ See It In Real Sketches

How line() is used in actual gallery sketches:

AI Color Mixer Lab

The line() function is utilized to visually represent the blending of RGB colors by drawing lines that connect the color values.

// Example snippet for color mixing using lines
stroke(r, g, b); line(x1, y1, x2, y2);...
View Sketch →

AI Maze Generator

The line() function is used to draw the walls of the maze, connecting each cell and creating the maze structure.

// Example snippet for maze walls
if (this.walls[0]) line(this.i, this.j, this.i + this.w, this.j);...
View Sketch →

AI Particle Fountain

The line() function is used to represent the ground and particles, creating a visual path for the particles as they move.

// Example snippet for drawing ground
stroke(210, 10, 60, 70); line(0, groundY, width, groundY);...
View Sketch →

🔀 Fun Function Combinations

Try asking the AI to combine line() with these:

line() + stroke()

→ Generates colored lines based on user input or predefined patterns.

Try: "Use line() to create a rainbow effect by cycling through colors with stroke()."

// Complete code for rainbow lines
for (let i = 0; i < 400; i += 10) {
  stroke(i % 255, 100, 150);
  line(i, 0, i, height);
}

âš ī¸ Common Mistakes & Fixes

❌ Mistake: Forgetting to set stroke() before using line().

🤔 Why it's wrong: If you do not set a stroke color, the line will default to black or may not be visible.

✅ Fix: // Corrected code stroke(255, 0, 0); // Set stroke color to red line(100, 100, 300, 300);

đŸ—ēī¸ Learning Path

💡 Project Ideas

  • Create a simple drawing app that uses line() to connect mouse points
  • Design a simple maze generator using line() to represent walls

🤖 Ask xelsed-alpha6 to Explain

Your prompt:

"Explain what line() does in p5.js"

Try this prompt in p5js.AI to see how the AI explains it!

Try in p5js.AI →

💡 Prompt AI to Write Code Using line()

Example prompt:

"Create something using line()"

🔧 Ask AI to Help Debug

When stuck, try:

"My line() isn't working, help me debug"

✨ Creative Combinations with AI

Ask AI to combine functions:

"Combine line() with other functions for interesting effects"

Ready to Try line()?

Open p5js.AI and ask the AI to help you use line() in your own creative project.

Start Coding with AI →