Skip to content

Instantly share code, notes, and snippets.

@Pamblam
Created July 21, 2020 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pamblam/42ed98c62e8636931c72d185e84225d0 to your computer and use it in GitHub Desktop.
Save Pamblam/42ed98c62e8636931c72d185e84225d0 to your computer and use it in GitHub Desktop.
Generate an image of text
/**
* Generate an image of text
* @param {String} text - The text to convert to an image
* @param {Object} options - The rendering options of the text and image
* @property {String} options.color - The color of the text
* @property {Number} options.font_size - The size of the text in pixels
* @property {String} options.font_face - The font face to use
* @property {String} options.font_style - The font style (normal|italic|oblique|initial|inherit)
* @property {String} options.font_variant - The font variant (normal|small-caps|initial|inherit)
* @property {String|Number} options.font_weight - The font weight (normal|bold|bolder|lighter|number|initial|inherit)
* @property {Number} options.padding - The padding around the text, in pixels
* @property {String} options.type - The format of the returned image (png|jpeg|webp)
* @property {Number} options.quality - A number between 0 and 1 indicating the quality of the output
* @returns {String} DataURI of the generated image
*/
function createTextImage(text, options) {
// Options
const color = options.color || 'black';
const font_size = options.font_size || 10;
const font_face = options.font_face || 'sans-serif';
const font_style = options.font_style || 'normal';
const font_variant = options.font_variant || 'normal';
const font_weight = options.font_weight || 'normal';
const padding = options.padding || 3;
const type = options.type || 'png';
const quality = options.quality || 0.92;
// Get a context to work with
const canvas = document.createElement('canvas');
const ctx = canvas.getContext("2d");
const font = `${font_style} ${font_variant} ${font_weight} ${font_size}px ${font_face}`;
// Get the text dimensions
ctx.font = font;
const textWidth = ctx.measureText(text).width;
// Set the canvas size
canvas.height = font_size + padding * 2;
canvas.width = textWidth + padding * 2;
// Reset the context because resizing the
// canvas clears the context
ctx.textBaseline = 'middle';
ctx.fillStyle = color;
ctx.font = font;
// Draw the text
ctx.fillText(text, padding, padding + font_size / 2);
// Convert the canvas to an image
return canvas.toDataURL(`image/${type}`, quality);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment