Create avatar with two letters


PHOTO EMBED

Tue Jan 19 2021 09:35:21 GMT+0000 (UTC)

Saved by @salitha.pathi #typescript

const { createCanvas, loadImage } = require("canvas");
const canvas = createCanvas(200, 200);

//TODO: replace with initials extraction logic.
var initials = "MM";

// Create a rectangular canvas which will become th image.
var context = canvas.getContext("2d");
canvas.width = canvas.height = 100;

// Draw the circle in the background using the randomColor.
context.fillStyle = randomColor;
context.beginPath();
context.ellipse(
  canvas.width / 2,
  canvas.height / 2, // Center x and y.
  canvas.width / 2,
  canvas.height / 2, // Horizontal and vertical "radius".
  0, // Rotation, useless for perfect circle.
  0,
  Math.PI * 2 // from and to angle: Full circle in radians.
);
context.fill();

context.font = "700 " + canvas.height / 3 + "px Helvetica";
context.fillStyle = fontColor;
// Make the text's center overlap the image's center.
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(initials, canvas.width / 2, canvas.height / 2);

// Show the image to the world.
console.log(canvas.toDataURL());
const fs = require("fs");
const out = fs.createWriteStream(__dirname + "/test.png");
const stream = canvas.createPNGStream();
stream.pipe(out);
out.on("finish", () => console.log("The PNG file was created."));

function getColors() {
  var randomColor =
    "#" + (0x1000000 | (Math.random() * 0xffffff)).toString(16).substr(1, 6);

  var fontColor = contrast(randomColor);

  return { background: randomColor, font: fontColor };
}

function rgbToPerceivedLuminance({ r, g, b }) {
  // used YIQ color space
  // Y component [0-255]
  return (r * 299 + g * 587 + b * 114) / 1000;
}

function hexToRgb(hex) {
  if (!hex || hex === undefined || hex === "") {
    return undefined;
  }

  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);

  return result
    ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16),
      }
    : undefined;
}

function contrast(colorHex, threshold = 128) {
  if (colorHex === undefined) {
    return "#000";
  }

  const rgb = hexToRgb(colorHex);

  if (rgb === undefined) {
    return "#000";
  }

  return rgbToPerceivedLuminance(rgb) >= threshold ? "#000" : "#fff";
}
content_copyCOPY