Skip to content

Instantly share code, notes, and snippets.

@leecrossley
Created July 18, 2013 08:48
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save leecrossley/6027780 to your computer and use it in GitHub Desktop.
Save leecrossley/6027780 to your computer and use it in GitHub Desktop.
A CodePen by Lee Crossley. Avatar Generator from Name - A name (first name and surname) is input and a canvas element is output using the initials from the name and a background colour (based on the first name first letter). The background colours are from from http://flatuicolors.com/ Now with retina support.
<canvas id="user-icon" width="256" height="256"></canvas>
var colours = ["#1abc9c", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#2c3e50", "#f1c40f", "#e67e22", "#e74c3c", "#ecf0f1", "#95a5a6", "#f39c12", "#d35400", "#c0392b", "#bdc3c7", "#7f8c8d"];
var name = "Lee Crossley",
nameSplit = name.split(" "),
initials = nameSplit[0].charAt(0).toUpperCase() + nameSplit[1].charAt(0).toUpperCase();
var charIndex = initials.charCodeAt(0) - 64,
colourIndex = charIndex % 20;
var canvas = document.getElementById("user-icon");
var context = canvas.getContext("2d");
var canvasWidth = $(canvas).attr("width"),
canvasHeight = $(canvas).attr("height"),
canvasCssWidth = canvasWidth,
canvasCssHeight = canvasHeight;
if (window.devicePixelRatio) {
$(canvas).attr("width", canvasWidth * window.devicePixelRatio);
$(canvas).attr("height", canvasHeight * window.devicePixelRatio);
$(canvas).css("width", canvasCssWidth);
$(canvas).css("height", canvasCssHeight);
context.scale(window.devicePixelRatio, window.devicePixelRatio);
}
context.fillStyle = colours[colourIndex - 1];
context.fillRect (0, 0, canvas.width, canvas.height);
context.font = "128px Arial";
context.textAlign = "center";
context.fillStyle = "#FFF";
context.fillText(initials, canvasCssWidth / 2, canvasCssHeight / 1.5);
@rasaworkshop
Copy link

colourIndex = charIndex % colours.length+1; is better Just in case people change the amount of colours.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment