74 lines
2.3 KiB
TypeScript
74 lines
2.3 KiB
TypeScript
export interface CertificateImageInput {
|
|
title: string;
|
|
rows: Array<{ label: string; value: string }>;
|
|
filename: string;
|
|
}
|
|
|
|
const FONT = '"Microsoft YaHei", "PingFang SC", sans-serif';
|
|
|
|
function wrap(ctx: CanvasRenderingContext2D, value: string, maxWidth: number): string[] {
|
|
const lines: string[] = [];
|
|
let line = '';
|
|
for (const char of Array.from(value || '-')) {
|
|
const next = line + char;
|
|
if (line && ctx.measureText(next).width > maxWidth) {
|
|
lines.push(line);
|
|
line = char;
|
|
} else {
|
|
line = next;
|
|
}
|
|
}
|
|
lines.push(line || '-');
|
|
return lines;
|
|
}
|
|
|
|
export function downloadCertificatePng(input: CertificateImageInput): void {
|
|
const width = 750;
|
|
const pad = 48;
|
|
const maxWidth = width - pad * 2;
|
|
const measure = document.createElement('canvas').getContext('2d');
|
|
if (!measure) return;
|
|
const lines: Array<{ text: string; font: string; gap: number; color: string }> = [];
|
|
measure.font = `bold 28px ${FONT}`;
|
|
for (const text of wrap(measure, input.title, maxWidth)) {
|
|
lines.push({ text, font: measure.font, gap: 36, color: '#143028' });
|
|
}
|
|
for (const row of input.rows) {
|
|
measure.font = `bold 14px ${FONT}`;
|
|
lines.push({ text: row.label, font: measure.font, gap: 22, color: '#5c6b66' });
|
|
measure.font = `16px ${FONT}`;
|
|
const wrapped = wrap(measure, row.value, maxWidth);
|
|
wrapped.forEach((text, index) => {
|
|
lines.push({ text, font: measure.font, gap: index === wrapped.length - 1 ? 28 : 22, color: '#1c1c1c' });
|
|
});
|
|
}
|
|
const height = pad * 2 + lines.reduce((sum, line) => sum + line.gap, 0);
|
|
const canvas = document.createElement('canvas');
|
|
canvas.width = width * 2;
|
|
canvas.height = height * 2;
|
|
const ctx = canvas.getContext('2d');
|
|
if (!ctx) return;
|
|
ctx.scale(2, 2);
|
|
ctx.fillStyle = '#f7f3ea';
|
|
ctx.fillRect(0, 0, width, height);
|
|
ctx.strokeStyle = '#0f766e';
|
|
ctx.lineWidth = 3;
|
|
ctx.strokeRect(18, 18, width - 36, height - 36);
|
|
let y = pad + 8;
|
|
for (const line of lines) {
|
|
ctx.font = line.font;
|
|
ctx.fillStyle = line.color;
|
|
ctx.fillText(line.text, pad, y);
|
|
y += line.gap;
|
|
}
|
|
canvas.toBlob((blob) => {
|
|
if (!blob) return;
|
|
const url = URL.createObjectURL(blob);
|
|
const link = document.createElement('a');
|
|
link.href = url;
|
|
link.download = input.filename;
|
|
link.click();
|
|
URL.revokeObjectURL(url);
|
|
}, 'image/png');
|
|
}
|