setup()
setup() runs once at the start and is where you initialize your canvas, load libraries, and attach event listeners. Here it bridges p5.js (the canvas) with HTML (the chat input) and preps text-to-speech. Notice the defensive programming: checking if p5.Speech exists prevents crashes if the library fails to load.
function setup() {
createCanvas(windowWidth, windowHeight);
background(240); // Canvas will be a background
// --- Debugging console logs ---
console.log("p5:", p5);
console.log("p5.sound:", typeof p5.sound); // Check type, not just value
console.log("p5.Speech:", typeof p5.Speech); // Check type
// --- End Debugging ---
// Initialize p5.Speech for Stella's responses
if (typeof p5.Speech !== 'undefined') { // Check if p5.Speech class is available
stellaSpeech = new p5.Speech();
stellaSpeech.setLang('en-US'); // Default language
stellaSpeech.setRate(1); // Normal speaking rate
stellaSpeech.setPitch(1); // Normal pitch
} else {
console.error("p5.Speech library (from p5.sound) not loaded correctly. Speech synthesis will be disabled.");
// Create a dummy object to prevent further crashes if p5.Speech is undefined
stellaSpeech = {
setLang: function() {},
setRate: function() {},
setPitch: function() {},
speaking: function() { return false; },
stop: function() {},
speak: function(text) { console.warn("Speech synthesis disabled: " + text); }
};
}
// Start the audio context on user gesture (send button click or enter key)
// This is required by browsers for audio to play.
userStartAudio();
// Get DOM elements for chat interface and log
userInput = select('#user-input');
sendButton = select('#send-button');
conversationLogDiv = select('#conversation-log');
// Event listener for sending messages
sendButton.mousePressed(sendMessage);
userInput.elt.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
sendMessage();
}
});
// Stella's initial greeting
addMessage("Stella", "Hello there! I'm Stella, your friendly chatbot. What's on your mind today?", false);
}
Line-by-line explanation (13 lines)
🔧 Subcomponents:
createCanvas(windowWidth, windowHeight);
Creates a full-window canvas that serves as the background for the chat interface
if (typeof p5.Speech !== 'undefined') {
Safely tests whether the p5.Speech library loaded before attempting to use it, preventing crashes
stellaSpeech = { setLang: function() {}, ... };
Creates a dummy object with no-op methods if p5.Speech fails, so the sketch continues running
userInput = select('#user-input');
Retrieves references to HTML elements so the sketch can read user input and display responses
sendButton.mousePressed(sendMessage);
Attaches click and Enter-key handlers to trigger message sending
createCanvas(windowWidth, windowHeight);- Creates a canvas that fills the entire browser window, serving as a subtle background behind the chat interface
console.log("p5:", p5);- Logs the p5 library object to the browser console for debugging; helps verify p5.js loaded correctly
if (typeof p5.Speech !== 'undefined') {- Checks whether the p5.Speech class exists before using it; prevents crashes if the library didn't load
stellaSpeech = new p5.Speech();- Creates a new text-to-speech object that Stella will use to speak her responses aloud
stellaSpeech.setLang('en-US');- Sets Stella's default speaking language to English (United States); can be changed later by user keywords
stellaSpeech.setRate(1);- Sets the speech rate to 1 (normal speed); values < 1 are slower, values > 1 are faster
stellaSpeech.setPitch(1);- Sets the pitch to 1 (normal); values < 1 lower the pitch, values > 1 raise it
stellaSpeech = { setLang: function() {}, ... };- If p5.Speech failed to load, creates a dummy object with empty methods so later calls don't crash
userStartAudio();- Initializes the browser's audio context; required on user interaction (like clicking Send) before audio can play
userInput = select('#user-input');- Uses p5.js's select() to grab the HTML input field element so we can read what the user types
sendButton.mousePressed(sendMessage);- Calls sendMessage() whenever the Send button is clicked
if (event.key === 'Enter') { sendMessage(); }- Lets users press Enter to send a message instead of clicking the button
addMessage("Stella", "Hello there! I'm Stella...", false);- Displays Stella's greeting message when the sketch first loads