Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save blopa/7f160eb9e0638f97a5cdd6fa9b39c64d to your computer and use it in GitHub Desktop.
Save blopa/7f160eb9e0638f97a5cdd6fa9b39c64d to your computer and use it in GitHub Desktop.
Code for post "How to automatically create thumbnails for your videos with Node.js"
const breakTextToFitCanvas = (ctx, text, maxWidth) => {
const words = text.split(' ');
const lines = [];
let currentLine = words[0];
for (let i = 1; i < words.length; i++) {
const word = words[i];
const { width } = ctx.measureText(`${currentLine} ${word}`);
if (width < maxWidth) {
currentLine += ` ${word}`;
} else {
lines.push(currentLine);
currentLine = word;
}
}
lines.push(currentLine);
return lines;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment