Skip to content

Instantly share code, notes, and snippets.

@webbower
Last active October 2, 2021 06:30
Show Gist options
  • Save webbower/27f3ba14705390e314a63ca72fe4d14b to your computer and use it in GitHub Desktop.
Save webbower/27f3ba14705390e314a63ca72fe4d14b to your computer and use it in GitHub Desktop.
Generate an image from text using the Canvas API
function generateImageFromText(text, width, height) {
// TODO Add auto-wrapping logic when text is too wide
// TODO Add tiered text scaling (if height > 200: font-size = 36; else if height > 100: font-size = 18; etc)
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
const fontSize = Math.min(height, 36);
ctx.fillStyle = '#212121';
ctx.font = `${fontSize}px 'Helvetica Neue', Helvetica, Arial, sans-serif`;
ctx.textBaseline = 'middle';
ctx.textAlign = 'center';
ctx.fillText(text, width / 2, height / 2, width);
return canvas.toDataURL('image/gif');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment