JavaScript

Generate Initials Avatar (Canvas)

by @admin
12h ago
Apr 28, 2026
Public
Draws a coloured circular avatar with up to two initials on an HTML5 Canvas and returns it as a data URL. Generates a consistent background colour from the name string so the same user always gets the same colour. Useful as a fallback when a user has no profile photo.
JavaScript
function initialsAvatar(name, size = 64) {
  const initials = name.split(' ').slice(0, 2).map((w) => w[0].toUpperCase()).join('');
  const hue      = [...name].reduce((sum, c) => sum + c.charCodeAt(0), 0) % 360;
  const canvas   = Object.assign(document.createElement('canvas'), { width: size, height: size });
  const ctx      = canvas.getContext('2d');

  ctx.fillStyle = `hsl(${hue}, 55%, 45%)`;
  ctx.beginPath();
  ctx.arc(size / 2, size / 2, size / 2, 0, Math.PI * 2);
  ctx.fill();

  ctx.fillStyle = '#fff';
  ctx.font      = `${Math.round(size * 0.38)}px sans-serif`;
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillText(initials, size / 2, size / 2);

  return canvas.toDataURL();
}

// Usage
const src = initialsAvatar('Alice Johnson');
document.querySelector('img.avatar').src = src;
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.