Skip to content

Instantly share code, notes, and snippets.

@rosswilson
Forked from leecrossley/index.html
Last active August 29, 2015 14:22
Show Gist options
  • Save rosswilson/51e59f1d106ff97aea4b to your computer and use it in GitHub Desktop.
Save rosswilson/51e59f1d106ff97aea4b to your computer and use it in GitHub Desktop.
<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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment