Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save blopa/194808b18adcaa355c463b7e8c05f8ef to your computer and use it in GitHub Desktop.
Save blopa/194808b18adcaa355c463b7e8c05f8ef to your computer and use it in GitHub Desktop.
Code for post "How to automatically create thumbnails for your videos with Node.js"
const addCenteredTextWithBackground = (
ctx,
text,
canvasWidth,
canvasHeight
) => {
const fontSize = 150;
ctx.font = `${fontSize}px Impact`;
const lines = text.split(' ');
const textHeight = fontSize * lines.length;
const rectWidth = canvasWidth;
const rectHeight = textHeight + 60;
const rectX = (canvasWidth - rectWidth) / 2;
const rectY = 300;
ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
ctx.fillRect(rectX, rectY, rectWidth, rectHeight);
ctx.fillStyle = 'white';
for (const [i, line] of lines.entries()) {
const textX = (canvasWidth - ctx.measureText(line).width) / 2;
const textY = rectY + fontSize * (i + 1);
ctx.fillText(line, textX, textY);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment