Files
drawlogo/js/core/poster-renderer.js
T
sgp 5bcd5ab0f2 feat(poster): 海报画布接入思源黑体(Noto Sans SC),SVG 导出走相对路径引用
- poster-renderer:注入 @font-face(按需加载,不阻塞首屏),文字默认字族 Noto Sans SC;新增 renderLinked(相对路径)与 renderEmbedded(PNG 内联,字体缺失自动降级)
- poster-exporter:SVG 导出用相对路径(约 1KB),PNG 仍内联字体保证自包含
- 实测:页面内字体生效(中文墨迹 7129 vs 回退 6952);导出的 SVG 站点内打开生效(8154 vs 7959);PNG 900x1200 正常
- poster.html 相关脚本统一 ?v=20261105a
2026-11-05 20:14:13 +08:00

168 lines
6.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 画个标 · 海报渲染引擎:元素数组 → SVG 字符串
* 中文字体:思源黑体(海报素材库 noto-sans-sc,OFL-1.1,OTF 直载)
* - 页面预览:注入 @font-face 后由浏览器直接渲染
* - 导出:SVG 作为 <img> 渲染时拿不到页面 @font-face,
* 故把实际用到的字重内联进 SVG(<defs><style> 内 data URI)
*/
const HGB_PosterRenderer = (function () {
'use strict';
const FONT = {
family: 'Noto Sans SC',
regular: 'js/data/posters/noto-sans-sc/files/NotoSansSC-Regular.otf',
bold: 'js/data/posters/noto-sans-sc/files/NotoSansSC-Bold.otf'
};
const FONT_STACK = FONT.family + ', SimHei, "Microsoft YaHei", sans-serif';
function esc(s) {
return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
/* ---------- 页面字体加载 ---------- */
/** 注入 @font-face(同步、不触发下载;浏览器在文字真正用到时按需加载,font-display:swap) */
function installFontFaces() {
if (typeof document === 'undefined') return false;
if (document.getElementById('hgb-poster-font')) return true;
const st = document.createElement('style');
st.id = 'hgb-poster-font';
st.textContent =
'@font-face{font-family:"' + FONT.family + '";src:url("' + FONT.regular + '") format("opentype");' +
'font-weight:400;font-style:normal;font-display:swap}' +
'@font-face{font-family:"' + FONT.family + '";src:url("' + FONT.bold + '") format("opentype");' +
'font-weight:700 900;font-style:normal;font-display:swap}';
document.head.appendChild(st);
return true;
}
let fontReady = null;
/** 显式等待字体可用(重复调用复用同一个 Promise) */
function ensureFonts() {
if (fontReady) return fontReady;
installFontFaces();
if (typeof document === 'undefined' || !document.fonts || !document.fonts.load) {
fontReady = Promise.resolve(false);
return fontReady;
}
fontReady = Promise.all([
document.fonts.load('400 24px "' + FONT.family + '"', '中文Aa'),
document.fonts.load('700 24px "' + FONT.family + '"', '中文Aa')
]).then(function () {
return document.fonts.check('400 24px "' + FONT.family + '"');
}).catch(function () { return false; });
return fontReady;
}
/* ---------- 导出字体内联 ---------- */
const b64Cache = {}; // 字体路径 -> Promise<base64>(进程内只读一次)
function fontBase64(url) {
if (!b64Cache[url]) {
b64Cache[url] = fetch(url).then(function (r) {
if (!r.ok) throw new Error('字体文件加载失败: ' + url);
return r.arrayBuffer();
}).then(function (buf) {
const bytes = new Uint8Array(buf);
const CHUNK = 0x8000;
let bin = '';
for (let i = 0; i < bytes.length; i += CHUNK) {
bin += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK));
}
return btoa(bin);
});
}
return b64Cache[url];
}
/** 元素实际用到的字重 */
function fontsUsed(elements) {
const list = elements || [];
let needRegular = false, needBold = false;
for (let i = 0; i < list.length; i++) {
if (list[i].type !== 'text') continue;
if (Number(list[i].fontWeight) >= 600) needBold = true; else needRegular = true;
}
return { needRegular: needRegular, needBold: needBold };
}
function faceRule(url, weight) {
return '@font-face{font-family:"' + FONT.family + '";src:url("' + url + '") format("opentype");' +
'font-weight:' + weight + ';font-style:normal}';
}
/** SVG 导出用:@font-face 走相对路径(文件小;留在站点内打开即生效,脱离站点回退系统字体) */
function linkFontDefs(elements) {
const used = fontsUsed(elements);
if (!used.needRegular && !used.needBold) return '';
let css = '';
if (used.needRegular) css += faceRule(FONT.regular, 400);
if (used.needBold) css += faceRule(FONT.bold, '700 900');
return '<defs><style type="text/css">' + css + '</style></defs>';
}
/** 按元素实际用到的字重生成内联 @font-face(PNG 导出用);无文字元素返回空串 */
function embedFontDefs(elements) {
const used = fontsUsed(elements);
if (!used.needRegular && !used.needBold) return Promise.resolve('');
const jobs = [];
if (used.needRegular) {
jobs.push(fontBase64(FONT.regular).then(function (b) {
return faceRule('data:font/otf;base64,' + b, 400);
}));
}
if (used.needBold) {
jobs.push(fontBase64(FONT.bold).then(function (b) {
return faceRule('data:font/otf;base64,' + b, '700 900');
}));
}
return Promise.all(jobs).then(function (rules) {
return '<defs><style type="text/css">' + rules.join('') + '</style></defs>';
});
}
/* ---------- 元素 → SVG ---------- */
function elToSvg(el) {
if (el.type === 'rect') {
return `<rect x="${el.x}" y="${el.y}" width="${el.w}" height="${el.h}" fill="${el.fill}"/>`;
}
if (el.type === 'circle') {
return `<circle cx="${el.cx}" cy="${el.cy}" r="${el.r}" fill="${el.fill}"/>`;
}
if (el.type === 'text') {
const anchor = el.align === 'middle' ? 'middle' : 'start';
// 字族用单引号包裹,避免与属性双引号冲突
const family = String(el.fontFamily || FONT_STACK).replace(/"/g, "'");
return `<text x="${el.x}" y="${el.y}" font-family="${esc(family)}" font-size="${el.fontSize}" font-weight="${el.fontWeight}" fill="${el.fill}" text-anchor="${anchor}" dominant-baseline="middle">${esc(el.text)}</text>`;
}
if (el.type === 'icon') {
return `<g transform="translate(${el.x} ${el.y}) scale(${el.w / 24})">${el.svg}</g>`;
}
return '';
}
function wrap(spec, body, defs) {
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${spec.w} ${spec.h}" width="${spec.w}" height="${spec.h}">${defs || ''}${body}</svg>`;
}
/** 页面预览用(同步,依赖已加载的 @font-face) */
function render(spec, elements) {
return wrap(spec, (elements || []).map(elToSvg).join(''), '');
}
/** SVG 导出用(同步、文件小):@font-face 相对路径引用站点内字体 */
function renderLinked(spec, elements) {
return wrap(spec, (elements || []).map(elToSvg).join(''), linkFontDefs(elements));
}
/** 导出用(异步,内联字体,离线可用);字体缺失时降级为系统字体栈,不阻断导出 */
function renderEmbedded(spec, elements) {
const body = (elements || []).map(elToSvg).join('');
return embedFontDefs(elements)
.then(function (defs) { return wrap(spec, body, defs); })
.catch(function () { return wrap(spec, body, ''); });
}
return { render, renderLinked, renderEmbedded, installFontFaces, ensureFonts, elToSvg, FONT, FONT_STACK };
})();