This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const words = [] // store word objects | |
function setup() { | |
createCanvas(800, 400) | |
background(0) | |
const str = 'Hello, world! Hi, there! Nice to meet you!' | |
const wordsStr = str.split(' ') | |
textSize(48) | |
// track word position | |
let x = 20 | |
let y = 60 | |
fill(255) | |
// iterate over each word | |
for (let i = 0; i < wordsStr.length; i++) { | |
const wordStr = wordsStr[i] // get current word | |
const wordStrWidth = textWidth(wordStr) // get current word width | |
const word = new Word(wordStr, x, y, i) | |
words.push(word) | |
x = x + wordStrWidth + textWidth(' ') // update x by word width + space character | |
// look ahead the next word - will it fit in the space? if not, line break | |
const nextWordStrWidth = textWidth(wordsStr[i+1]) || 0 | |
if (x > width - nextWordStrWidth) { | |
y += 40 // line height, sort of | |
x = 20 // reset x position | |
} | |
} | |
for (let i = 0; i < words.length; i++) { | |
const word = words[i] // retrive word object | |
word.display() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment