Last active
October 2, 2021 06:30
-
-
Save webbower/27f3ba14705390e314a63ca72fe4d14b to your computer and use it in GitHub Desktop.
Generate an image from text using the Canvas API
This file contains hidden or 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
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