Monogram Image by Name

by Alen Subasic

HTML

<img src="">

CSS

img {
  border: 1px solid #ccc;
  border-radius: 4px;
  box-shadow: 6px 6px 2px 1px rgba(0, 0, 0, .15);
}

JavaScript

function createMonogram(name) {
  // Create a canvas element
  const canvas = document.createElement('canvas');
  // Set the width and height of the canvas
  canvas.width = 100;
  canvas.height = 100;
  // Get the 2D context of the canvas
  const ctx = canvas.getContext('2d');
  // Draw the name on the canvas
  ctx.font = 'bold 72px Arial';
  ctx.fillStyle = 'black';
  // (First Letter , Left, Top)
  ctx.fillText(name[0], 25, 75);
  // Create an image element
  const image = document.createElement('img');
  // Set the src of the image to the canvas
  image.src = canvas.toDataURL();
  // Return the image
  return image;
}

const img = document.querySelector('img')

/******* CHANGE Amazon to any name *******/
img.src = createMonogram('Dice').src