event 🌱 Beginner

keyPressed()

The keyPressed() function in p5.js is an essential tool for capturing keyboard input, allowing creative coders to interact with their sketches in real-time. This function is particularly useful for creating dynamic, responsive art and games, where user input can influence visuals or behavior. For example, you might use keyPressed() to change the color of a shape or move an object around the canvas, making your artwork come alive through interaction.

📖 p5.js Reference →

🧠 See The Whole Picture

Picture your canvas as a stage and the keyPressed() function as a stage manager. The stage manager watches for specific cues from the audience (key presses) and directs the actors (shapes and colors) to perform certain actions in response. Each key press is like a signal that changes the performance dynamically.

📖 Visual Learner's Guide

The Big Picture:

When you press a key, something changes on the canvas, like a color shift or movement. It's like having a remote control for your artwork.

Visual Analogy:

Think of keyPressed() as a doorbell for your art. When you ring the bell (press a key), something happens inside the house (the canvas).

The Numbers Decoded:

Instead of numbers, you use letters and symbols to tell the program what to do. For example, pressing 'r' turns the canvas red, while 'g' turns it green.

Connection Map:

Before you draw anything, you set up the canvas in setup(). Then, each time you press a key, keyPressed() checks which key it was and changes the scene accordingly.

Common Gotcha:

Many beginners forget to define what happens when a key is pressed. Without an action, pressing a key will not change anything on the canvas!

🔄 How It Works

This diagram illustrates the flow of execution, showing how your code interacts with the keyPressed function and affects the canvas.

📝 Syntax

📖 How to Read This

Read keyPressed(key) as: 'Listen for the key press event. If the specified key is pressed, execute the associated action.' The parentheses are like a command center where you specify which key to listen for.

keyPressed(param1, param2, ...)

Example: keyPressed('a')

🔀 Different Ways to Call It

keyPressed(key)

Use this form to detect a single key press, allowing for simple interactions, such as changing colors or moving shapes.

keyPressed('a') → Pressing 'a' might change the color of a shape to red.
keyPressed(key, action)

This form allows for more complex interactions, enabling different actions based on the key pressed.

keyPressed('ArrowRight', moveRight); → Pressing the right arrow key moves an object to the right.

â†Šī¸ What It Returns

Type: void

The keyPressed() function doesn't return a value; it triggers an action directly on the canvas, similar to a button press that causes an immediate response in your sketch.

đŸ“Ĩ What Goes In

Imagine you are giving the keyPressed() function a command to listen for a specific key on your keyboard. When you press down on that key, it triggers a hidden action, like pulling a string that makes a puppet dance. The letters and symbols you type are like the puppet's movements, responding to your cues.

📤 What Happens

When the keyPressed() function detects a key press, it immediately executes the defined action, such as changing the background color or moving a shape across the canvas. This creates an interactive experience where the user feels directly connected to the artwork, influencing it with their inputs.

Parameters

key String required

A String represents a specific key on the keyboard, such as 'a', '1', or 'ArrowUp'.

This parameter controls which key press to detect. Common values are letters, numbers, and arrow keys. At 0 or empty, no key is detected.

Range: Any character or string representing a key.

Examples: 'a' → The letter 'a' key is pressed. '1' → The number '1' key is pressed. 'ArrowUp' → The up arrow key is pressed.
action Function optional

A Function is a block of code that can be executed when a specific key is detected.

This parameter defines the action to take when the key is pressed, such as moving an object or changing colors.

Range: Any function that can be executed.

Examples: moveRight → Moves an object right when the right arrow key is pressed.

💡 How Parameters Work Together

Think of the key parameter as a doorway you can unlock with your keyboard. Each key you press is like a key that opens a different room with unique activities inside. The action parameter is what happens once you enter that room - maybe you change the color of a shape or move an object around the canvas.

đŸ’ģ Working Example

// Complete working example with comments
function setup() {
  createCanvas(400, 400);
  background(220);
}

function draw() {
  // The canvas updates with each frame
}

function keyPressed() {
  if (key === 'r') {
    background(255, 0, 0); // Change background to red
  }
  if (key === 'g') {
    background(0, 255, 0); // Change background to green
  }
}
Try This Code →

âš™ī¸ How It Works

When p5.js executes the keyPressed() function, it listens for keyboard events. If a key is pressed, it captures that event and checks the specified key against the conditions defined in your code. Depending on which key was pressed, it then executes the corresponding action, like changing colors or moving objects, updating the canvas in real-time.

🎓 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 keyPressed() to create a responsive color-changing sketch."

Why it works: Giving the AI a persona helps it understand the CONTEXT and style you want, making the output more tailored.

📋 Recipe Pattern

Ask for step-by-step instructions

"Give me step-by-step code to use keyPressed() to create an interactive sketch that changes colors based on key presses."

Why it works: Breaking down into steps helps you understand each part and learn incrementally, making complex ideas more digestible.

📝 Template Pattern

Provide a structure for the AI to fill in

"Use this template: setup creates canvas, draw uses keyPressed() with specific parameters to create an interactive effect."

Why it works: Templates give the AI clear constraints, resulting in more predictable output that aligns with your vision.

🔄 Refinement Pattern

Start simple and iterate

"Start with a basic keyPressed() example. Then I'll ask you to add more features like animations and interactions."

Why it works: Building up gradually helps you understand each addition and not get overwhelmed, allowing for better learning.

đŸŽ¯ Direct Prompts - Name the Function

Tell the AI exactly which function to use:

Direct

"Create a sketch that changes the background color when different keys are pressed."

💡 Why this is good: This prompt provides clear instructions and a specific goal, making it straightforward for the AI to generate relevant code.

📚 What you learn: Understanding how to capture user input and respond with visual changes.

📝 Sample Output:
// function keyPressed() to change background colors based on keys pressed.
Direct

"Use keyPressed() to create a sketch that moves a shape around based on arrow key inputs."

💡 Why this is good: This template sets up a clear structure for the AI, guiding it to produce organized and relevant code.

📚 What you learn: Learn how to manipulate shapes and create interactive experiences.

📝 Sample Output:
// function keyPressed() to move a shape in response to arrow keys.

🔮 Indirect Prompts - Describe What You Want

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

Indirect

"Describe a way to create an interactive sketch that responds to keyboard input for color changes."

💡 Why this is good: This teaches you can describe WHAT you want without knowing the function name, fostering creativity in communication.

īŋŊ What you learn: You learn to articulate your visual intent and the desired interaction.

📝 Sample Output:
// Code that uses keyPressed() to change colors based on user input.

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

How keyPressed() is used in actual gallery sketches:

Interactive Color Changer

The keyPressed() function is used to detect specific key presses that change the background color dynamically, creating an engaging user experience.

// function keyPressed() to change background colors based on keys pressed....

🔀 Fun Function Combinations

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

keyPressed() + random()

→ Randomly changes the color of a shape each time a key is pressed.

Try: "Create a sketch that randomly changes colors when you press any key."

// function keyPressed() to change color randomly.

âš ī¸ Common Mistakes & Fixes

❌ Mistake: Not defining actions for key presses.

🤔 Why it's wrong: Beginners often forget to include the actions that should occur when a key is pressed, leading to no visible change.

✅ Fix: Ensure that your keyPressed() function includes conditional statements with defined actions for each key.

đŸ—ēī¸ Learning Path

💡 Project Ideas

  • Create a simple game where the player moves a character with the keyboard
  • Build an interactive art piece that changes colors or shapes with user input

🤖 Ask xelsed-alpha6 to Explain

Your prompt:

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

Example prompt:

"Create something using keyPressed()"

🔧 Ask AI to Help Debug

When stuck, try:

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

✨ Creative Combinations with AI

Ask AI to combine functions:

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

📚 Related Functions

Ready to Try keyPressed()?

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

Start Coding with AI →