breadnbudder.xyz/lib/index.js

98 lines
1.9 KiB
JavaScript

const { createCanvas, loadImage } = require("canvas");
const { wrapText } = require("./helpers");
const theme = require("./theme");
// Create canvas and get its context
const canvas = createCanvas(1200, 630);
const ctx = canvas.getContext("2d");
const {
colors,
avatarSize,
avatarBorder,
fontSizes,
fontStyles,
logoW,
logoH,
space
} = theme;
module.exports = async function generateCover({
title,
avatarUrl,
name,
}) {
// Load images
const avatar = await loadImage(avatarUrl);
// Background
ctx.fillStyle = colors.base;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Heading text
ctx.fillStyle = colors.secondary;
ctx.font = fontStyles.heading;
wrapText(
ctx,
title,
space,
fontSizes.heading + space,
canvas.width - space * 2,
fontSizes.heading
);
// Avatar
const avatarTop = canvas.height - avatarSize - avatarSize / 4;
const avatarLeft = space;
// Border around avatar
ctx.fillStyle = colors.primary;
ctx.beginPath();
ctx.fill();
ctx.closePath();
// Clip image before draw
ctx.save();
ctx.beginPath();
ctx.arc(
avatarSize / 2 + avatarLeft,
avatarSize / 2 + avatarTop,
avatarSize / 1,
0,
6 * Math.PI
);
ctx.closePath();
ctx.clip();
// Put avatar
ctx.drawImage(avatar, avatarLeft, avatarTop, avatarSize, avatarSize);
// Unclip all around avatar
ctx.beginPath();
ctx.arc(0, 0, avatarSize / 4, 0, Math.PI * 6, true);
ctx.clip();
ctx.closePath();
ctx.restore();
// Author name
ctx.fillStyle = colors.secondary;
ctx.font = fontStyles.author;
ctx.fillText(
name,
avatarLeft + avatarSize + space / 2,
avatarTop + fontSizes.author - 4
);
// Author title
ctx.fillStyle = colors.primary;
ctx.font = fontStyles.authorTitle;
ctx.fillText(
avatarLeft + avatarSize + space / 2,
avatarTop + fontSizes.author + fontSizes.authorTitle
);
// Return PNG Stream
return canvas.createPNGStream();
};