Skip to content

Instantly share code, notes, and snippets.

@zymr-keshav
Created March 28, 2018 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zymr-keshav/01d89e60b56fea7390f77c7fe7c1b20f to your computer and use it in GitHub Desktop.
Save zymr-keshav/01d89e60b56fea7390f77c7fe7c1b20f to your computer and use it in GitHub Desktop.
create image with name initials using html5vcanvas
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Use Initials Image</title>
</head>
<body>
<img src="" / >
<script>
(function() {
const getAvatarImage = (name = 'A B') => {
console.log('fullname: ', name);
const canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 200;
canvas.style.height = '200px';
canvas.style.width = '200px';
const context = canvas.getContext('2d');
context.scale(1, 1);
context.save();
context.fillStyle = 'whitesmoke';
context.font = 'normal bold 36px/1.2 sans-serif';
context.textBaseline = 'middle';
context.textAlign = 'center';
context.strokeStyle = '#879da6';
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeRect(10, 10, 180, 180);
// const initials = `${name.first.charAt(0)} ${name.last.charAt(0)}`;
const initials = 'K M';
let width = context.measureText(initials).width;
/// draw background rect assuming height of font
context.fillRect(0, 0, width, parseInt(initials, 10));
/// text color
context.fillStyle = '#879da6';
/// draw text on top
context.fillText(initials.toUpperCase(), canvas.width / 2, canvas.width / 2, 100);
const data = canvas.toDataURL();
return data;
};
function LoadImages() {
let myImage = new Image();
myImage.src = getAvatarImage('Keshav', 'Mohta');
document.body.appendChild(myImage);
}
LoadImages();
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment