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
This commit is contained in:
sgp
2026-11-05 20:14:13 +08:00
parent 409cc766a1
commit 5bcd5ab0f2
3 changed files with 162 additions and 16 deletions
+16 -5
View File
@@ -1,5 +1,7 @@
/**
* 画个标 · 海报导出:SVG / PNG(按画布规格导出)
* - SVG:@font-face 用相对路径引用站点内思源黑体(文件小,留在站点内打开即正确渲染)
* - PNG:SVG 作为 <img> 渲染时拿不到页面 @font-face,故内联字重后再栅格化
*/
const HGB_PosterExporter = (function () {
'use strict';
@@ -8,6 +10,16 @@ const HGB_PosterExporter = (function () {
return HGB_PosterRenderer.render(spec, elements);
}
/** SVG 导出用(相对路径字体,文件小) */
function buildSvgLinked(spec, elements) {
return HGB_PosterRenderer.renderLinked(spec, elements);
}
/** 内联字体后的 SVG(Promise<string>,PNG 栅格化用) */
function buildSvgEmbedded(spec, elements) {
return HGB_PosterRenderer.renderEmbedded(spec, elements);
}
function download(name, blob) {
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
@@ -18,14 +30,13 @@ const HGB_PosterExporter = (function () {
}
function exportSvg(spec, elements, base) {
const svg = buildSvg(spec, elements);
const svg = buildSvgLinked(spec, elements);
download((base || '海报') + '.svg', new Blob([svg], { type: 'image/svg+xml' }));
}
/** 渲染 SVG 到位图并下载(scale 控制放大倍数,默认 1) */
function svgToCanvas(spec, elements, scale) {
return new Promise((resolve, reject) => {
const svg = buildSvg(spec, elements);
return buildSvgEmbedded(spec, elements).then(svg => new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
const w = Math.round(spec.w * scale), h = Math.round(spec.h * scale);
@@ -37,7 +48,7 @@ const HGB_PosterExporter = (function () {
};
img.onerror = () => reject(new Error('SVG 渲染失败'));
img.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg);
});
}));
}
async function exportPng(spec, elements, base, scale) {
@@ -46,5 +57,5 @@ const HGB_PosterExporter = (function () {
download((base || '海报') + '.png', blob);
}
return { buildSvg, exportSvg, exportPng, svgToCanvas };
return { buildSvg, buildSvgLinked, buildSvgEmbedded, exportSvg, exportPng, svgToCanvas };
})();
+138 -5
View File
@@ -1,13 +1,127 @@
/**
* 画个标 · 海报渲染引擎:元素数组 → 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}"/>`;
@@ -17,7 +131,9 @@ const HGB_PosterRenderer = (function () {
}
if (el.type === 'text') {
const anchor = el.align === 'middle' ? 'middle' : 'start';
return `<text x="${el.x}" y="${el.y}" font-family="SimHei, Microsoft YaHei, sans-serif" font-size="${el.fontSize}" font-weight="${el.fontWeight}" fill="${el.fill}" text-anchor="${anchor}" dominant-baseline="middle">${esc(el.text)}</text>`;
// 字族用单引号包裹,避免与属性双引号冲突
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>`;
@@ -25,10 +141,27 @@ const HGB_PosterRenderer = (function () {
return '';
}
function render(spec, elements) {
const body = (elements || []).map(elToSvg).join('');
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${spec.w} ${spec.h}" width="${spec.w}" height="${spec.h}">${body}</svg>`;
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>`;
}
return { render };
/** 页面预览用(同步,依赖已加载的 @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 };
})();