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

triangle()

The triangle() function in p5.js allows you to create triangles by specifying the coordinates of their three vertices. Creative coders use it to construct geometric shapes, design characters, and even create intricate patterns. For example, you could use triangle() to form a simple character in a game or to create artistic compositions in generative art.

📖 p5.js Reference →

🧠 See The Whole Picture

Imagine the canvas as a large sheet of graph paper. Each triangle function call plants three dots at the specified coordinates (the vertices), then connects these dots with lines to form the triangle shape. The area inside the lines gets filled with whatever color you set using fill().

📖 Visual Learner's Guide

The Big Picture:

When you run this code, you will see a triangle drawn on a light gray background.

Visual Analogy:

Think of it like connecting dots with a pencil. You place three dots on your paper (the vertices) and then draw lines between them to form a triangle.

The Numbers Decoded:

x=200 and y=150 mean the first point is positioned 200 pixels from the left and 150 pixels from the top. The other two pairs of numbers do the same for the other two points.

Connection Map:

The fill() function sets the inside color of the triangle before you draw it. The stroke() function defines the outline color, which outlines the triangle made by triangle().

Common Gotcha:

Remember, the coordinates are based on the top-left corner of the canvas as (0,0), not the center.

🔄 How It Works

This diagram illustrates the flow from your code to the triangle drawing on the canvas, showing how the triangle function directly interacts with the canvas.

📝 Syntax

📖 How to Read This

Read triangle(x1, y1, x2, y2, x3, y3) as: Draw a triangle with the first vertex at (x1, y1), the second at (x2, y2), and the third at (x3, y3). The parentheses contain the coordinates needed to plot each corner of the triangle.

triangle(param1, param2, param3, param4, param5, param6)

Example: triangle(200, 150, 250, 300, 150, 300)

🔀 Different Ways to Call It

triangle(x1, y1, x2, y2, x3, y3)

Use this form to define a triangle by specifying the X and Y coordinates of each vertex.

triangle(100, 100, 150, 200, 50, 200); → A triangle with vertices at (100, 100), (150, 200), and (50, 200).

â†Šī¸ What It Returns

Type: void

The triangle() function does not return any value but instead directly draws a triangle onto the canvas using the specified coordinates.

đŸ“Ĩ What Goes In

You give triangle() six numbers. The first two are like GPS coordinates for the first vertex, the next two for the second vertex, and the last two for the third vertex. These coordinates determine where each point of the triangle will be placed on the canvas.

📤 What Happens

triangle() takes your coordinates and immediately paints a triangle on the canvas. It uses the active fill() color for the inside and stroke() color for the outline, creating a visible shape based on your input.

Parameters

x1, y1, x2, y2, x3, y3 Number required

Number means any digit like 100, 3.14, or -50. Think of it as anything you could measure with a ruler or count.

These parameters control the coordinates of the triangle's vertices. For example, x1 and y1 set the position of the first vertex, while x2, y2, and x3, y3 do the same for the other two vertices.

Range: Any number within the canvas dimensions.

Examples: 0, 0 → A point at the top left corner of the canvas. 200, 200 → A point in the center of the canvas. 400, 400 → A point at the bottom right corner of the canvas.

💡 How Parameters Work Together

Think of it like setting up a tent. The vertices (x1,y1), (x2,y2), and (x3,y3) are the points where the tent stakes go into the ground. The shape of the triangle is defined by how far apart these stakes are placed.

đŸ’ģ Working Example

// Complete working example with comments
function setup() {
  createCanvas(400, 400);
  fill(100, 150, 255); // Set fill color
  stroke(0); // Set outline color
}

function draw() {
  background(220);
  triangle(200, 150, 250, 300, 150, 300); // Draw a triangle
}
Try This Code →

âš™ī¸ How It Works

When p5.js executes triangle(), it first reads the six parameters provided. It calculates where to place the vertices on the canvas based on these coordinates. Once the vertices are determined, it draws lines between them to create the triangle shape. The fill color is applied before the triangle is drawn, and any stroke settings will outline the triangle accordingly.

🎓 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 triangle() to create a dynamic mountain landscape."

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 triangle() to create a star shape. Start simple, then add complexity."

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 triangle() with specific parameters to make a tree."

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

🔄 Refinement Pattern

Start simple and iterate

"Start with a basic triangle() 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

"Use triangle() to create an abstract art piece with overlapping triangles in different colors."

💡 Why this is good: This prompt clearly specifies the function and desired visual outcome, guiding the AI effectively.

📚 What you learn: Learn to manipulate shapes and colors to create complex visuals.

📝 Sample Output:
// Code showing overlapping triangles with varying colors.
Direct

"Create a simple character using triangle() for the body, head, and limbs."

💡 Why this is good: The template structure helps the AI understand what components to include in the character design.

📚 What you learn: Understand how to compose multiple shapes to create a complete figure.

📝 Sample Output:
// Complete code for a character made of triangles.

🔮 Indirect Prompts - Describe What You Want

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

Indirect

"Describe a shape that has three corners and looks like a mountain peak."

💡 Why this is good: This teaches you to describe the visual intent without naming specific functions.

īŋŊ What you learn: Learn to communicate visual ideas effectively, allowing the AI to infer the correct function.

📝 Sample Output:
// Code showing that triangle() was the chosen function for the shape.

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

How triangle() is used in actual gallery sketches:

AI Quest Master v2 - Fantasy RPG - XeLseDai

In this sketch, triangle() is used to create trees as part of the forest scene, enhancing the visual storytelling aspect.

// Inside the drawScene function, triangle() is used to draw trees.
triangle(100, 250, 130, 150, 160, 250);...

🔀 Fun Function Combinations

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

triangle() + rotate() + translate()

→ Creates dynamic, rotated triangles that can be moved around the canvas.

Try: "Use triangle() with rotation and translation to create a spinning star."

// Example of a spinning triangle that moves across the canvas.
function draw() {
  translate(width / 2, height / 2);
  rotate(frameCount * 0.01);
  triangle(-50, -50, 50, -50, 0, 50);
}

âš ī¸ Common Mistakes & Fixes

❌ Mistake: Forgetting to set fill() or stroke() before calling triangle().

🤔 Why it's wrong: Without specifying colors, the triangle might default to transparent or an unexpected color.

✅ Fix: Always set fill() and stroke() before drawing shapes.

đŸ—ēī¸ Learning Path

💡 Project Ideas

  • Create a simple game character using triangles.
  • Design a dynamic landscape using triangles to represent mountains and trees.

🤖 Ask xelsed-alpha6 to Explain

Your prompt:

"Explain what triangle() 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 triangle()

Example prompt:

"Create something using triangle()"

🔧 Ask AI to Help Debug

When stuck, try:

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

✨ Creative Combinations with AI

Ask AI to combine functions:

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

Ready to Try triangle()?

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

Start Coding with AI →