Text Conversation
← All Butter documentationA chat made of message bubbles.
Each message is one item of a createMultiFieldArray, made of two fields: a select for the sender and an input for the text.
let messages
function setup() {
createCanvas(windowWidth, windowHeight)
messages = createMultiFieldArray((i) => {
const sender = createSelect()
sender.option('Me', 'me')
sender.option('Them', 'them')
// Alternate the senders to start with
sender.selected(i % 2 === 0 ? 'me' : 'them')
return {
sender,
text: createInput(''),
}
}, { min: 1, max: 8, default: 2 })
}
function draw() {
clear()
noStroke()
textSize(18)
textAlign(LEFT, CENTER)
let y = 20
for (const message of messages.value()) {
const mine = message.sender.value() === 'me'
const label = message.text.value()
const w = fontWidth(label) + 28
const x = mine ? width - w - 16 : 16
fill(mine ? '#0b84fe' : '#e5e5ea')
rect(x, y, w, 40, 20)
fill(mine ? 'white' : 'black')
text(label, x + 14, y + 20)
y += 52
}
}

A few things to notice:
- The function receives the item's index, so the starting sender can differ between items.
senderis created in a variable first because it needs.option()and.selected()calls. Returning it under the keysenderis what names the field.messages.value()is read indraw, so new and removed messages show up right away.