Skip to content

Instantly share code, notes, and snippets.

@lieldulev
Created August 30, 2012 23:33
Show Gist options
  • Save lieldulev/3545076 to your computer and use it in GitHub Desktop.
Save lieldulev/3545076 to your computer and use it in GitHub Desktop.
A javascript function to get an filler image (data url) for any text
// @param [string] text - required. Text to render.
// @param [string] width - required. Image height.
// @param [string] height - required. Image width.
// @param [string] bgcolor - optional. Background color. Default dark grey.
// @param [string] fgcolor - optional. Text color. Default white.
// @param [string] shadow - optional. Shadow color. Default is no shadow.
function imageFromText(text, width, height, bgcolor, fgcolor, shadow)
{
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext('2d');
ctx.fillStyle = bgcolor || '#666';
ctx.fillRect(0,0,width,height);
var fontSizes = [48, 42, 36, 28, 14, 12, 10, 5];
ctx.globalAlpha = 1;
ctx.textBaseline = 'middle';
var textDimensions,
i = 0;
do {
ctx.font = 'bold '+fontSizes[i++] + 'px Geneva';
textDimensions = ctx.measureText(text);
} while (textDimensions.width >= canvas.width && i < fontSizes.length);
if(shadow){
ctx.fillStyle = shadow;
ctx.fillText(text, ((canvas.width - textDimensions.width) / 2)+2, ((canvas.height / 2)+2))
}
ctx.fillStyle = fgcolor || 'white';
// if(fgcolor){ctx.fillStyle = fgcolor;}
ctx.fillText(text, (canvas.width - textDimensions.width) / 2, (canvas.height) / 2);
return canvas.toDataURL('image/png');
}
// EXAMPLE
img_element = document.getElementById('test');
img_element.src = imageFromText("My Super Awesome Long Text","640","480",'#488CFA','#dfefff','#008')
<img id='test'>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment