Skip to content

Instantly share code, notes, and snippets.

@vctrfrnndz
Created May 18, 2015 17:06
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save vctrfrnndz/fab6f839aaed0de566b0 to your computer and use it in GitHub Desktop.
Save vctrfrnndz/fab6f839aaed0de566b0 to your computer and use it in GitHub Desktop.
Generate SVG letter avatar
function drawCircle(text, size, color) {
var textSize = Math.ceil(size / 2.5);
var font = 'Proxima Nova, proxima-nova, HelveticaNeue-Light, Helvetica Neue Light, Helvetica Neue, Helvetica, Arial, Lucida Grande, sans-serif';
var colors = ["#1abc9c", "#16a085", "#f1c40f", "#f39c12", "#2ecc71", "#27ae60", "#e67e22", "#d35400", "#3498db", "#2980b9", "#e74c3c", "#c0392b", "#9b59b6", "#8e44ad", "#bdc3c7", "#34495e", "#2c3e50", "#95a5a6", "#7f8c8d", "#ec87bf", "#d870ad", "#f69785", "#9ba37e", "#b49255", "#b49255", "#a94136"];
var colorIndex = Math.floor((text.charCodeAt(0) - 65) % colors.length);
var finalColor = color || colors[colorIndex];
var template = [
'<svg height="' + size + '" width="' + size + '" style="background: ' + finalColor + '">',
'<text text-anchor="middle" x="50%" y="50%" dy="0.35em" fill="white" font-size="' + textSize + '" font-family="' + font + '">' + text.toUpperCase() + '</text>',
'</svg>'
];
return template.join('');
}
//Tests
document.body.innerHTML += drawCircle('r', 200);
document.body.innerHTML += drawCircle('n', 150);
document.body.innerHTML += drawCircle('RR', 120, '#f00');
document.body.innerHTML += drawCircle('bn', 100, '#f00');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment