@qnd/badge
v1.0.0
Published
Library for adding badges to images using 2D canvas API.
Downloads
6
Readme
[@qnd/badge] Badge drawing for all
Library for adding badges to images using 2D canvas API.

[💀] Example
Function to set a badge on the favicon:
import {
ALIGN,
type BadgeStyle,
type CanvasExportOptions,
canvasToBlob,
drawBadge,
} from "@qnd/badge";
// Constants
const PNG_OPTIONS = {
type: "image/png",
quality: 1,
} satisfies CanvasExportOptions;
const DEFAULT_STYLE = {
verticalAlign: ALIGN.center,
horizontalAlign: ALIGN.center,
fontFamily: '"Courier New", monospace',
bg: { fillStyle: "#fff" },
fg: { fillStyle: "#000" },
} satisfies BadgeStyle;
// Setup
const ORIGINAL = document.head.querySelector<HTMLLinkElement>(
"link[rel=icon]",
)!;
const IMAGE = new Image();
IMAGE.src = ORIGINAL.href;
const { promise, resolve, reject } = Promise.withResolvers();
IMAGE.onerror = reject;
IMAGE.onload = resolve;
await promise;
const SUBSTITUTE = ORIGINAL.cloneNode() as HTMLLinkElement;
SUBSTITUTE.type = PNG_OPTIONS.type;
const CANVAS = new OffscreenCanvas(0, 0);
// Favicon badge setting time
const setFaviconBadge = async (text: string) => {
URL.revokeObjectURL(SUBSTITUTE.href);
if (!text.length) {
return SUBSTITUTE.replaceWith(ORIGINAL);
}
drawBadge(CANVAS, IMAGE, text, DEFAULT_STYLE);
const blob = await canvasToBlob(CANVAS, PNG_OPTIONS);
SUBSTITUTE.href = URL.createObjectURL(blob);
ORIGINAL.replaceWith(SUBSTITUTE);
};[💾] Installation
Choose your fighter:
npm install @qnd/badge
yarn add @qnd/badge
pnpm install @qnd/badge
deno install jsr:@qnd/badge[🖥️] Tasks
# Transpile to JS + D.TS
deno task transpile
# Run publishing in dry mode
deno task dry-run
# Prepare for publishing (does all of the above)
deno task prepare
# Publish to JSR and NPM
deno task publish[📝] License
This work is licensed under Apache-2.0 (see NOTICE).
