Last active
June 26, 2017 19:42
-
-
Save vaporic/7448261079c704c53c3215f5b7626bde to your computer and use it in GitHub Desktop.
Avatar Generator from Name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<canvas id="user-icon" width="256" height="256"></canvas> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var colours = ["#1abc9c", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#2c3e50", "#f1c40f", "#e67e22", "#e74c3c", "#95a5a6", "#f39c12", "#d35400", "#c0392b", "#bdc3c7", "#7f8c8d"]; | |
var name = "Hugo Espinosa", | |
nameSplit = name.split(" "), | |
initials = nameSplit[0].charAt(0).toUpperCase() + nameSplit[1].charAt(0).toUpperCase(); | |
var charIndex = initials.charCodeAt(0) - 65, | |
colourIndex = charIndex % 19; | |
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]; | |
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