mirror of
https://github.com/YuleBest/FontMM.git
synced 2026-12-04 03:11:48 +08:00
perf(tools): 字体编辑性能重构 — Canvas 预览 + 快照重置 + lazy 解析 + numpy
- 预览彻底摆脱字体文件: fontTools 提取轮廓点 (getCoordinates 展开复合字形),
主线程 Canvas 二次贝塞尔渲染 + advance 布局/折行/行距 (previewRenderer.ts)
- 22.7MB/29422 字形中文字体实测: 首次预览 2.1s, 滑条调整 12ms (原 15-30s)
- 数据经 JSON 传递, 规避 PyProxy postMessage 克隆失败
- 编辑引擎重构:
- TTFont(lazy=True) + 字形懒快照: 首次预览只解析用到的字形
- 快照-重置: list 浅拷贝快照 (coordinates/flags/endPts/bytecode/组件),
每次编辑从原始快照重置再变换, 多次调整不累积
- numpy 批量矩阵变换 (简单字形), 复合组件内联算术 — 导出提速 62s->11.5s
- 修复: items()/instructions/transform 缺失, Program.fromBytecode 返回 None,
组件 transform 2x2 嵌套/tr[2] 越界 (Eth 等复合字形导出失败)
- 移除滑动手势切页 (仅底栏点击, 防误触)
- numpy whl 本地化进 webroot
This commit is contained in:
1 parent
1ad9e70758
commit
4186f9009a
6 files changed
+396
-125
No files matched your search
Binary file not shown.
+216
-18
@@ -36,47 +36,217 @@ def analyze(data):
|
||||
// 编辑字体: 字形轮廓缩放 + 偏移, advance 随缩放; 丢弃可变字体表
|
||||
const EDIT_PY = `
|
||||
from fontTools.ttLib import TTFont
|
||||
from fontTools.pens.transformPen import TransformPen
|
||||
from fontTools.pens.ttGlyphPen import TTGlyphPen
|
||||
from fontTools.misc.transform import Transform
|
||||
from fontTools.ttLib.tables._g_l_y_f import Glyph, GlyphComponent, GlyphCoordinates
|
||||
from fontTools.ttLib.tables.ttProgram import Program
|
||||
import numpy
|
||||
from io import BytesIO
|
||||
|
||||
def edit_font(data, scale, dx, dy, letter_spacing=0, line_spacing=0):
|
||||
# 缓存: 原始字体对象 + 字形快照 (list 浅拷贝, 毫秒级; 避免 deepcopy 整个字体)
|
||||
_FONT_CACHE = {}
|
||||
_GLYPH_ORIG = {}
|
||||
_HMTX_ORIG = {}
|
||||
_LINEGAP_ORIG = {}
|
||||
|
||||
def _snapshot_glyph(g):
|
||||
if g is None:
|
||||
return None
|
||||
if g.numberOfContours is not None and g.numberOfContours >= 0:
|
||||
program = getattr(g, 'program', None)
|
||||
bc = None
|
||||
if program is not None and program.bytecode:
|
||||
bc = list(program.bytecode)
|
||||
return ('simple', g.numberOfContours,
|
||||
list(g.coordinates) if hasattr(g, 'coordinates') else [],
|
||||
list(g.flags) if hasattr(g, 'flags') else [],
|
||||
list(g.endPtsOfContours) if hasattr(g, 'endPtsOfContours') else [],
|
||||
bc)
|
||||
comps = []
|
||||
for c in g.components:
|
||||
tr_raw = getattr(c, 'transform', None)
|
||||
tr = None
|
||||
if tr_raw is not None:
|
||||
tr = (tr_raw[0][0], tr_raw[0][1], tr_raw[1][0], tr_raw[1][1])
|
||||
comps.append((c.glyphName, c.x, c.y, tr, c.flags))
|
||||
return ('composite', comps)
|
||||
|
||||
def _restore_glyph(snap):
|
||||
if snap is None:
|
||||
return None
|
||||
g = Glyph()
|
||||
if snap[0] == 'simple':
|
||||
g.numberOfContours = snap[1]
|
||||
if snap[2]:
|
||||
g.coordinates = GlyphCoordinates(snap[2])
|
||||
if snap[3]:
|
||||
g.flags = snap[3]
|
||||
if snap[4]:
|
||||
g.endPtsOfContours = snap[4]
|
||||
if snap[5]:
|
||||
g.program = Program()
|
||||
g.program.fromBytecode(bytes(snap[5]))
|
||||
else:
|
||||
g.program = Program()
|
||||
else:
|
||||
g.numberOfContours = -1
|
||||
g.components = []
|
||||
for name2, x, y, tr, flags in snap[1]:
|
||||
c = GlyphComponent()
|
||||
c.glyphName = name2
|
||||
c.x = x
|
||||
c.y = y
|
||||
c.flags = flags
|
||||
if tr is not None:
|
||||
c.transform = [[tr[0], tr[1]], [tr[2], tr[3]]]
|
||||
g.components.append(c)
|
||||
g.program = Program()
|
||||
return g
|
||||
|
||||
def _ensure_snapshot(data_key, data):
|
||||
if data_key in _FONT_CACHE:
|
||||
return
|
||||
# lazy=True: glyf 字形按需解析, 大字体首次预览只解析用到的字形
|
||||
f = TTFont(BytesIO(data), fontNumber=0, lazy=True)
|
||||
_FONT_CACHE[data_key] = f
|
||||
_GLYPH_ORIG[data_key] = {}
|
||||
_HMTX_ORIG[data_key] = dict(f['hmtx'].metrics)
|
||||
_LINEGAP_ORIG[data_key] = (
|
||||
f['hhea'].lineGap if 'hhea' in f else 0,
|
||||
f['OS/2'].sTypoLineGap if 'OS/2' in f else 0,
|
||||
)
|
||||
|
||||
def _orig_glyph(data_key, name):
|
||||
# 懒快照单个字形
|
||||
snap = _GLYPH_ORIG[data_key].get(name, '?')
|
||||
if snap == '?':
|
||||
f = _FONT_CACHE[data_key]
|
||||
g = f['glyf'][name] if name in f['glyf'] else None
|
||||
snap = _snapshot_glyph(g)
|
||||
_GLYPH_ORIG[data_key][name] = snap
|
||||
return snap
|
||||
|
||||
# Glyph 无 transform 方法: numpy 批量变换简单字形点, 复合字形合并组件矩阵
|
||||
def _apply_matrix(g, matrix):
|
||||
if g is None:
|
||||
return
|
||||
nc = g.numberOfContours
|
||||
if nc is not None and nc >= 0 and hasattr(g, 'coordinates'):
|
||||
coords = g.coordinates
|
||||
xx, xy, yx, yy, dx, dy = matrix
|
||||
arr = numpy.array(coords, dtype=numpy.float64)
|
||||
arr = arr @ numpy.array([[xx, xy], [yx, yy]], dtype=numpy.float64)
|
||||
arr = arr + numpy.array([dx, dy], dtype=numpy.float64)
|
||||
arr = numpy.rint(arr).astype(numpy.int32)
|
||||
g.coordinates = GlyphCoordinates(arr.tolist())
|
||||
elif nc == -1:
|
||||
xx, xy, yx, yy, dx, dy = matrix
|
||||
for c in g.components:
|
||||
tr = getattr(c, 'transform', None)
|
||||
if tr:
|
||||
c.transform = [[xx * tr[0][0] + xy * tr[1][0], xx * tr[0][1] + xy * tr[1][1]],
|
||||
[yx * tr[0][0] + yy * tr[1][0], yx * tr[0][1] + yy * tr[1][1]]]
|
||||
px = c.x * xx + c.y * xy + dx
|
||||
py = c.x * yx + c.y * yy + dy
|
||||
c.x, c.y = round(px), round(py)
|
||||
|
||||
def _glyph_names_for_text(f, text):
|
||||
cmap = f.getBestCmap()
|
||||
names = set()
|
||||
for ch in text:
|
||||
cp = ord(ch)
|
||||
if cp in cmap:
|
||||
names.add(cmap[cp])
|
||||
return names
|
||||
|
||||
def edit_font(data_key, data, scale, dx, dy, letter_spacing=0, line_spacing=0,
|
||||
preview_chars=None):
|
||||
try:
|
||||
f = TTFont(BytesIO(data), fontNumber=0)
|
||||
_ensure_snapshot(data_key, data)
|
||||
f = _FONT_CACHE[data_key]
|
||||
if 'glyf' not in f:
|
||||
return {'ok': False, 'error': '仅支持 TrueType (.ttf) 字体'}
|
||||
gs = f.getGlyphSet()
|
||||
glyf = f['glyf']
|
||||
matrix = Transform(scale, 0, 0, scale, dx, dy)
|
||||
for name in f.getGlyphOrder():
|
||||
g = glyf[name]
|
||||
pen = TTGlyphPen(gs)
|
||||
tpen = TransformPen(pen, matrix)
|
||||
g.draw(tpen, glyf)
|
||||
glyf[name] = pen.glyph()
|
||||
# 预览模式: 只重置+变换预览文本涉及的字形; 导出时全量
|
||||
if preview_chars:
|
||||
names = _glyph_names_for_text(f, preview_chars)
|
||||
else:
|
||||
names = set(f.getGlyphOrder())
|
||||
for name in names:
|
||||
snap = _orig_glyph(data_key, name)
|
||||
if snap is not None:
|
||||
glyf[name] = _restore_glyph(snap)
|
||||
_apply_matrix(glyf[name], matrix)
|
||||
# 度量: 从原始快照重算 (advance 全量调整)
|
||||
hmtx = f['hmtx']
|
||||
for name in f.getGlyphOrder():
|
||||
advance, lsb = hmtx[name]
|
||||
orig_hmtx = _HMTX_ORIG[data_key]
|
||||
for name, (advance, lsb) in orig_hmtx.items():
|
||||
if advance:
|
||||
# 字间距: 叠加到 advance width (可正可负)
|
||||
hmtx[name] = (max(1, round(advance * scale + letter_spacing)), lsb)
|
||||
# 行间距: 叠加到 hhea.lineGap 与 OS/2.sTypoLineGap
|
||||
hmtx.metrics[name] = (max(1, round(advance * scale + letter_spacing)), lsb)
|
||||
else:
|
||||
hmtx.metrics[name] = (0, lsb)
|
||||
if line_spacing:
|
||||
orig_line_gap, orig_typo_gap = _LINEGAP_ORIG[data_key]
|
||||
if 'hhea' in f:
|
||||
f['hhea'].lineGap = max(0, round(f['hhea'].lineGap + line_spacing))
|
||||
f['hhea'].lineGap = max(0, round(orig_line_gap + line_spacing))
|
||||
if 'OS/2' in f:
|
||||
f['OS/2'].sTypoLineGap = max(0, round(f['OS/2'].sTypoLineGap + line_spacing))
|
||||
f['OS/2'].sTypoLineGap = max(0, round(orig_typo_gap + line_spacing))
|
||||
# 编辑后可变轴已无意义, 丢弃
|
||||
for t in ('fvar', 'gvar', 'avar', 'STAT', 'cvar'):
|
||||
if t in f:
|
||||
del f[t]
|
||||
# 注: 预览模式不做 subset (subset 会污染缓存字体对象), 直接输出完整字体
|
||||
out = BytesIO()
|
||||
f.save(out)
|
||||
return {'ok': True, 'data': out.getvalue()}
|
||||
except Exception as e:
|
||||
return {'ok': False, 'error': str(e)}
|
||||
|
||||
# 预览: 提取预览文本涉及字形的轮廓点 (不生成字体文件, 毫秒级)
|
||||
# 返回 { glyphs: {unicode码点: {pts: [[x,y,on],...], end: [...], adv: advance}}, upem, lineGap }
|
||||
def build_preview(data_key, data, text, scale, dx, dy, letter_spacing=0, line_spacing=0):
|
||||
try:
|
||||
_ensure_snapshot(data_key, data)
|
||||
f = _FONT_CACHE[data_key]
|
||||
if 'glyf' not in f:
|
||||
return {'ok': False, 'error': '仅支持 TrueType (.ttf) 字体'}
|
||||
cmap = f.getBestCmap()
|
||||
glyf = f['glyf']
|
||||
hmtx = f['hmtx']
|
||||
matrix = Transform(scale, 0, 0, scale, dx, dy)
|
||||
orig_glyphs = _GLYPH_ORIG[data_key]
|
||||
glyphs = {}
|
||||
for ch in text:
|
||||
cp = ord(ch)
|
||||
if cp in glyphs:
|
||||
continue
|
||||
name = cmap.get(cp)
|
||||
if name is None:
|
||||
continue
|
||||
snap = _orig_glyph(data_key, name)
|
||||
if snap is None:
|
||||
continue
|
||||
g = _restore_glyph(snap)
|
||||
_apply_matrix(g, matrix)
|
||||
# getCoordinates 自动展开复合字形
|
||||
coords, endPts, flags = g.getCoordinates(glyf)
|
||||
pts = []
|
||||
for i, (x, y) in enumerate(coords):
|
||||
on = 1 if flags[i] & 0x01 else 0
|
||||
pts.append([round(x), round(y), on])
|
||||
advance, _ = hmtx[name]
|
||||
glyphs[str(cp)] = {'pts': pts, 'end': list(endPts), 'adv': max(1, round(advance * scale + letter_spacing))}
|
||||
line_gap = _LINEGAP_ORIG[data_key][0] if line_spacing else 0
|
||||
import json
|
||||
# JSON 序列化传递 (避免 PyProxy 经 postMessage 克隆失败)
|
||||
return {'ok': True, 'json': json.dumps({
|
||||
'glyphs': glyphs,
|
||||
'upem': f['head'].unitsPerEm,
|
||||
'lineGap': max(0, round(line_gap + line_spacing)),
|
||||
})}
|
||||
except Exception as e:
|
||||
return {'ok': False, 'error': str(e)}
|
||||
|
||||
# 修改 name 表字段 (Windows Unicode 平台, 写入或替换)
|
||||
def update_names(data, names):
|
||||
try:
|
||||
@@ -102,6 +272,7 @@ self.onmessage = async (e: MessageEvent) => {
|
||||
const { loadPyodide } = await import('pyodide');
|
||||
py = await loadPyodide({ indexURL: payload.indexURL });
|
||||
await py.loadPackage('fonttools');
|
||||
await py.loadPackage('numpy');
|
||||
await py.runPythonAsync(ANALYZE_PY + EDIT_PY);
|
||||
self.postMessage({ id, ok: true });
|
||||
} else if (type === 'analyze') {
|
||||
@@ -120,16 +291,43 @@ self.onmessage = async (e: MessageEvent) => {
|
||||
names: r.names,
|
||||
error: r.error,
|
||||
});
|
||||
} else if (type === 'preview') {
|
||||
const r = py.globals
|
||||
.get('build_preview')(
|
||||
payload.dataKey,
|
||||
py.toPy(new Uint8Array(payload.data)),
|
||||
payload.text,
|
||||
payload.scale,
|
||||
payload.dx,
|
||||
payload.dy,
|
||||
payload.letterSpacing ?? 0,
|
||||
payload.lineSpacing ?? 0,
|
||||
)
|
||||
.toJs({ dict_converter: Object.fromEntries });
|
||||
if (r.ok) {
|
||||
const parsed = JSON.parse(r.json);
|
||||
self.postMessage({
|
||||
id,
|
||||
ok: true,
|
||||
glyphs: parsed.glyphs,
|
||||
upem: parsed.upem,
|
||||
lineGap: parsed.lineGap,
|
||||
});
|
||||
} else {
|
||||
self.postMessage({ id, ok: false, error: r.error });
|
||||
}
|
||||
} else if (type === 'edit') {
|
||||
const bytes = py.toPy(new Uint8Array(payload.data));
|
||||
const r = py.globals
|
||||
.get('edit_font')(
|
||||
payload.dataKey,
|
||||
bytes,
|
||||
payload.scale,
|
||||
payload.dx,
|
||||
payload.dy,
|
||||
payload.letterSpacing ?? 0,
|
||||
payload.lineSpacing ?? 0,
|
||||
payload.previewChars ?? null,
|
||||
)
|
||||
.toJs({ dict_converter: Object.fromEntries });
|
||||
if (r.ok) {
|
||||
|
||||
@@ -362,85 +362,6 @@ function showView(index: number) {
|
||||
if (target === 2) loadTestFonts();
|
||||
}
|
||||
|
||||
// 手势滑动切换 (跟手拖拽 + 边界限制)
|
||||
let touchStartX = 0;
|
||||
let touchStartY = 0;
|
||||
let touchDragging = false;
|
||||
// touchmove 节流: 每帧最多写入一次 transform, 避免慢滑时高频样式操作压垮主线程
|
||||
let rafPending = false;
|
||||
let lastDragDx = 0;
|
||||
|
||||
viewTrack.addEventListener(
|
||||
'touchstart',
|
||||
(e) => {
|
||||
// 滑条等可横向拖动组件内的触摸不触发页面切换 (composedPath 穿透 shadow DOM)
|
||||
if (e.composedPath().some((el) => el instanceof Element && el.tagName === 'MD-SLIDER')) {
|
||||
return;
|
||||
}
|
||||
touchStartX = e.touches[0].clientX;
|
||||
touchStartY = e.touches[0].clientY;
|
||||
touchDragging = true;
|
||||
},
|
||||
{ passive: true },
|
||||
);
|
||||
|
||||
viewTrack.addEventListener(
|
||||
'touchmove',
|
||||
(e) => {
|
||||
if (!touchDragging) return;
|
||||
const dx = e.touches[0].clientX - touchStartX;
|
||||
const dy = e.touches[0].clientY - touchStartY;
|
||||
// 仅横向意图时跟手拖动 (避免干扰页面纵向滚动)
|
||||
if (Math.abs(dx) > Math.abs(dy) && Math.abs(dx) > 8) {
|
||||
e.preventDefault();
|
||||
viewTrack.style.transition = 'none';
|
||||
lastDragDx = dx;
|
||||
if (rafPending) return;
|
||||
rafPending = true;
|
||||
requestAnimationFrame(() => {
|
||||
rafPending = false;
|
||||
// touchend/touchcancel 后丢弃残留的拖拽更新, 避免覆盖切换动画
|
||||
if (!touchDragging) return;
|
||||
// 边界阻尼: 首页右拖 / 末页左拖 阻力减半, 增强边界手感
|
||||
let effDx = lastDragDx;
|
||||
if (
|
||||
(currentIndex === 0 && lastDragDx > 0) ||
|
||||
(currentIndex === views.length - 1 && lastDragDx < 0)
|
||||
) {
|
||||
effDx = lastDragDx / 3;
|
||||
}
|
||||
viewTrack.style.transform = `translateX(calc(${-currentIndex * 100}% + ${effDx}px))`;
|
||||
});
|
||||
}
|
||||
},
|
||||
{ passive: false },
|
||||
);
|
||||
|
||||
viewTrack.addEventListener(
|
||||
'touchend',
|
||||
(e) => {
|
||||
touchDragging = false;
|
||||
viewTrack.style.transition = '';
|
||||
const dx = e.changedTouches[0].clientX - touchStartX;
|
||||
const canPrev = currentIndex > 0;
|
||||
const canNext = currentIndex < views.length - 1;
|
||||
if (Math.abs(dx) > 60 && ((dx < 0 && canNext) || (dx > 0 && canPrev))) {
|
||||
showView(currentIndex + (dx < 0 ? 1 : -1));
|
||||
} else {
|
||||
// 未达阈值回弹: 仅恢复轨道位置, 不调用 showView (避免重置页面滚动位置)
|
||||
viewTrack.style.transform = `translateX(${-currentIndex * 100}%)`;
|
||||
}
|
||||
},
|
||||
{ passive: true },
|
||||
);
|
||||
|
||||
// 触摸被系统打断 (来电/手势等): 复位拖拽状态并回弹
|
||||
viewTrack.addEventListener('touchcancel', () => {
|
||||
touchDragging = false;
|
||||
viewTrack.style.transition = '';
|
||||
viewTrack.style.transform = `translateX(${-currentIndex * 100}%)`;
|
||||
});
|
||||
|
||||
// 悬浮按钮滚动隐藏: 向下滚动移出视口, 向上滚动出现 (每页独立滚动)
|
||||
views.forEach((view, i) => {
|
||||
let lastY = 0;
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
// Canvas 字形预览渲染: 用 fontTools 提取的轮廓点直接绘制, 不依赖字体文件
|
||||
|
||||
export interface GlyphPreviewData {
|
||||
pts: [number, number, number][]; // [x, y, onCurve]
|
||||
end: number[];
|
||||
adv: number;
|
||||
}
|
||||
|
||||
export interface PreviewData {
|
||||
glyphs: Record<string, GlyphPreviewData>; // key: unicode 码点
|
||||
upem: number;
|
||||
lineGap: number;
|
||||
}
|
||||
|
||||
// 绘制单个轮廓段 (TrueType 二次贝塞尔规则, 含首尾 off-curve 处理)
|
||||
function traceContour(ctx: CanvasRenderingContext2D, seg: [number, number, number][]): void {
|
||||
const n = seg.length;
|
||||
if (n < 2) return;
|
||||
// 起点: 首点 on-curve -> 直接用; 否则用末点或首末中点
|
||||
let i = 0;
|
||||
let sx: number;
|
||||
let sy: number;
|
||||
if (seg[0][2] === 1) {
|
||||
sx = seg[0][0];
|
||||
sy = seg[0][1];
|
||||
i = 1;
|
||||
} else if (seg[n - 1][2] === 1) {
|
||||
sx = seg[n - 1][0];
|
||||
sy = seg[n - 1][1];
|
||||
} else {
|
||||
sx = (seg[0][0] + seg[n - 1][0]) / 2;
|
||||
sy = (seg[0][1] + seg[n - 1][1]) / 2;
|
||||
}
|
||||
ctx.moveTo(sx, -sy);
|
||||
let visited = 0;
|
||||
const maxIter = n * 2 + 2;
|
||||
while (visited < n && i < maxIter) {
|
||||
const p = seg[i % n];
|
||||
if (p[2] === 1) {
|
||||
ctx.lineTo(p[0], -p[1]);
|
||||
i++;
|
||||
visited++;
|
||||
} else {
|
||||
const next = seg[(i + 1) % n];
|
||||
if (next[2] === 1) {
|
||||
ctx.quadraticCurveTo(p[0], -p[1], next[0], -next[1]);
|
||||
i += 2;
|
||||
visited += 2;
|
||||
} else {
|
||||
// 连续 off-curve: 中间隐含 on-curve 点为中点
|
||||
ctx.quadraticCurveTo(p[0], -p[1], (p[0] + next[0]) / 2, -(p[1] + next[1]) / 2);
|
||||
i++;
|
||||
visited++;
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx.closePath();
|
||||
}
|
||||
|
||||
function traceGlyph(ctx: CanvasRenderingContext2D, g: GlyphPreviewData): void {
|
||||
if (!g || g.pts.length === 0) return;
|
||||
ctx.beginPath();
|
||||
let start = 0;
|
||||
for (const endIdx of g.end) {
|
||||
traceContour(ctx, g.pts.slice(start, endIdx + 1));
|
||||
start = endIdx + 1;
|
||||
}
|
||||
if (start < g.pts.length) traceContour(ctx, g.pts.slice(start));
|
||||
}
|
||||
|
||||
export interface RenderOptions {
|
||||
fontSize: number; // CSS 像素字号
|
||||
color: string;
|
||||
}
|
||||
|
||||
// 渲染预览文本到 canvas (自动适配宽高/折行)
|
||||
export function renderPreview(
|
||||
canvas: HTMLCanvasElement,
|
||||
data: PreviewData,
|
||||
text: string,
|
||||
opts: RenderOptions,
|
||||
): void {
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
const cssW = canvas.clientWidth || 320;
|
||||
const cssH = canvas.clientHeight || 200;
|
||||
canvas.width = Math.round(cssW * dpr);
|
||||
canvas.height = Math.round(cssH * dpr);
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return;
|
||||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
ctx.clearRect(0, 0, cssW, cssH);
|
||||
ctx.fillStyle = opts.color;
|
||||
|
||||
const pxPerUnit = opts.fontSize / data.upem;
|
||||
const pad = 8;
|
||||
const lineHeight = opts.fontSize + data.lineGap * pxPerUnit;
|
||||
let x = pad;
|
||||
let y = pad + opts.fontSize; // 基线
|
||||
|
||||
for (const ch of text) {
|
||||
if (ch === '\n') {
|
||||
x = pad;
|
||||
y += lineHeight;
|
||||
continue;
|
||||
}
|
||||
const g = data.glyphs[String(ch.codePointAt(0))];
|
||||
if (g) {
|
||||
ctx.save();
|
||||
ctx.translate(x, y);
|
||||
ctx.scale(pxPerUnit, pxPerUnit);
|
||||
traceGlyph(ctx, g);
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
x += g.adv * pxPerUnit;
|
||||
} else {
|
||||
x += opts.fontSize * 0.5; // 缺失字形占位
|
||||
}
|
||||
if (x > cssW - pad) {
|
||||
x = pad;
|
||||
y += lineHeight;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1134,3 +1134,10 @@ md-dialog {
|
||||
.ft-names-extra {
|
||||
animation: tool-page-in 0.2s ease;
|
||||
}
|
||||
|
||||
// ---- 字体编辑: Canvas 预览 ----
|
||||
.ft-preview-canvas {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 200px;
|
||||
}
|
||||
+50
-28
@@ -1,6 +1,7 @@
|
||||
import '@material/web/button/filled-button.js';
|
||||
import { exec } from './ksu';
|
||||
import { FontFilePicker } from './fontPicker';
|
||||
import { renderPreview, type PreviewData } from './previewRenderer';
|
||||
|
||||
// ---------------- 工具框架 ----------------
|
||||
// 每个工具是一个独立页面: 注册 ToolDef 后自动出现在工具列表, 点击进入其页面。
|
||||
@@ -313,6 +314,7 @@ class FontEditorPage {
|
||||
private infoCard!: HTMLElement;
|
||||
private editPanel!: HTMLElement;
|
||||
private previewEl!: HTMLElement;
|
||||
private previewCanvas!: HTMLCanvasElement;
|
||||
private openBtn!: HTMLButtonElement & { disabled: boolean };
|
||||
private exportBtn!: HTMLButtonElement & { disabled: boolean };
|
||||
private openProgress!: any;
|
||||
@@ -331,7 +333,6 @@ class FontEditorPage {
|
||||
private loading = false;
|
||||
|
||||
private originalBytes: Uint8Array | null = null;
|
||||
private lastEditedBytes: Uint8Array | null = null;
|
||||
private fileName = '';
|
||||
private hasNameChanges = false;
|
||||
private picker: FontFilePicker | null = null;
|
||||
@@ -345,6 +346,7 @@ class FontEditorPage {
|
||||
this.infoCard = page.querySelector('#ft-info')!;
|
||||
this.editPanel = page.querySelector('#ft-edit')!;
|
||||
this.previewEl = page.querySelector('#ft-preview')!;
|
||||
this.previewCanvas = page.querySelector('#ft-preview-canvas')!;
|
||||
this.openBtn = page.querySelector('#ft-open-btn') as any;
|
||||
this.exportBtn = page.querySelector('#ft-export-btn') as any;
|
||||
this.openProgress = page.querySelector('#ft-open-progress') as any;
|
||||
@@ -362,7 +364,7 @@ class FontEditorPage {
|
||||
(page.querySelector('#ft-export-done') as any).open = false;
|
||||
});
|
||||
// 预览文本自定义: 点击预览区 -> 对话框
|
||||
const previewBox = page.querySelector('#ft-preview-box') as HTMLElement | null;
|
||||
const previewBox = page.querySelector('.ft-preview') as HTMLElement | null;
|
||||
const previewInput = page.querySelector('#ft-preview-input') as any;
|
||||
const previewDialog = page.querySelector('#ft-preview-dialog') as any;
|
||||
previewBox?.addEventListener('click', () => {
|
||||
@@ -375,7 +377,7 @@ class FontEditorPage {
|
||||
page.querySelector('#ft-preview-save')?.addEventListener('click', () => {
|
||||
if (previewDialog) previewDialog.open = false;
|
||||
this.previewText = previewInput.value ?? '';
|
||||
this.previewEl.textContent = this.previewText;
|
||||
void this.applyEdit(); // 重新提取新字符轮廓并渲染
|
||||
});
|
||||
// 展开/收起更多 name 字段
|
||||
const moreBtn = page.querySelector('#ft-names-more') as HTMLElement | null;
|
||||
@@ -561,7 +563,7 @@ class FontEditorPage {
|
||||
}
|
||||
}
|
||||
|
||||
// 执行编辑 (Worker 内, 防抖) 并刷新预览
|
||||
// 执行预览 (Worker 提取轮廓, Canvas 渲染) — 不生成字体文件, 大字体也毫秒级
|
||||
private async applyEdit(): Promise<void> {
|
||||
if (!this.pyReady || !this.originalBytes) return;
|
||||
const scale = Number(this.scaleSlider?.value ?? 100) / 100;
|
||||
@@ -571,55 +573,74 @@ class FontEditorPage {
|
||||
const lineSpacing = Number(this.llSlider?.value ?? 0);
|
||||
this.previewEl.classList.add('ft-preview-busy');
|
||||
try {
|
||||
const result = await this.call('edit', {
|
||||
const result = await this.call('preview', {
|
||||
dataKey: this.fileName || 'font',
|
||||
data: this.originalBytes,
|
||||
text: this.previewText,
|
||||
scale,
|
||||
dx,
|
||||
dy,
|
||||
letterSpacing,
|
||||
lineSpacing,
|
||||
});
|
||||
this.lastEditedBytes = result.data;
|
||||
await this.showPreview(result.data);
|
||||
if (!result.glyphs) throw new Error(result.error ?? '预览失败');
|
||||
this.renderCanvas(result);
|
||||
this.exportBtn.disabled = false;
|
||||
} catch (e) {
|
||||
this.previewCanvas.hidden = true;
|
||||
this.previewEl.hidden = false;
|
||||
this.previewEl.textContent = `编辑失败: ${(e as Error).message}`;
|
||||
} finally {
|
||||
this.previewEl.classList.remove('ft-preview-busy');
|
||||
}
|
||||
}
|
||||
|
||||
// 用编辑后的字体字节加载 FontFace 预览 (主线程, 快)
|
||||
private async showPreview(bytes: Uint8Array): Promise<void> {
|
||||
try {
|
||||
const buf = bytes.buffer.slice(
|
||||
bytes.byteOffset,
|
||||
bytes.byteOffset + bytes.byteLength,
|
||||
) as ArrayBuffer;
|
||||
const face = new FontFace('fontmm-edit-preview', buf);
|
||||
await face.load();
|
||||
document.fonts.add(face);
|
||||
this.previewEl.style.fontFamily = '"fontmm-edit-preview"';
|
||||
this.previewEl.textContent = this.previewText;
|
||||
} catch {
|
||||
this.previewEl.textContent = '预览失败 (字体可能不含预览所需字形)';
|
||||
}
|
||||
// Canvas 渲染预览 (主题色填充)
|
||||
private renderCanvas(data: PreviewData): void {
|
||||
const color =
|
||||
getComputedStyle(document.documentElement)
|
||||
.getPropertyValue('--md-sys-color-on-surface')
|
||||
.trim() || '#1c1b1f';
|
||||
renderPreview(this.previewCanvas, data, this.previewText, {
|
||||
fontSize: 36,
|
||||
color,
|
||||
});
|
||||
this.previewCanvas.hidden = false;
|
||||
this.previewEl.hidden = true;
|
||||
}
|
||||
|
||||
// 导出: 字形编辑结果 (若有 name 修改则链式合并) -> base64 分块写盘
|
||||
private async exportFont(): Promise<void> {
|
||||
if (!this.originalBytes || !this.lastEditedBytes) return;
|
||||
if (!this.originalBytes) return;
|
||||
this.exportBtn.disabled = true;
|
||||
this.statusEl.textContent = '正在导出 (分块写入, 请稍候)...';
|
||||
this.statusEl.textContent = '正在全量编辑字形(大字体可能需要 1-3 分钟)...';
|
||||
this.exportProgress.value = 0;
|
||||
this.exportProgress.hidden = false;
|
||||
try {
|
||||
let finalBytes = this.lastEditedBytes;
|
||||
// 全量编辑 (非预览模式): 所有字形变换
|
||||
const scale = Number(this.scaleSlider?.value ?? 100) / 100;
|
||||
const dx = Number(this.dxSlider?.value ?? 0);
|
||||
const dy = Number(this.dySlider?.value ?? 0);
|
||||
const letterSpacing = Number(this.lsSlider?.value ?? 0);
|
||||
const lineSpacing = Number(this.llSlider?.value ?? 0);
|
||||
const editResult = await this.call('edit', {
|
||||
dataKey: this.fileName || 'font',
|
||||
data: this.originalBytes,
|
||||
scale,
|
||||
dx,
|
||||
dy,
|
||||
letterSpacing,
|
||||
lineSpacing,
|
||||
// 不传 previewChars: 全量编辑
|
||||
});
|
||||
let finalBytes = editResult.data;
|
||||
if (this.hasNameChanges) {
|
||||
this.statusEl.textContent = '正在写入字体信息...';
|
||||
const names = this.collectNames();
|
||||
const r = await this.call('updateNames', { data: finalBytes, names });
|
||||
finalBytes = r.data;
|
||||
}
|
||||
this.statusEl.textContent = '正在导出 (分块写入, 请稍候)...';
|
||||
const b64 = bytesToBase64(finalBytes);
|
||||
const base = this.fileName.replace(/\.[^.]+$/, '') || 'font';
|
||||
const outName = `edited-${base}.ttf`;
|
||||
@@ -627,7 +648,7 @@ class FontEditorPage {
|
||||
const tmp = `${WEBROOT_DIR}/work/export.tmp`;
|
||||
|
||||
await exec(`rm -f '${tmp}' && mkdir -p '${outDir}'`);
|
||||
const CHUNK = 30000; // base64 字符, 约 22KB 二进制
|
||||
const CHUNK = 60000; // base64 字符, 约 45KB 二进制
|
||||
const total = Math.ceil(b64.length / CHUNK);
|
||||
for (let i = 0; i < b64.length; i += CHUNK) {
|
||||
const part = b64.slice(i, i + CHUNK);
|
||||
@@ -730,12 +751,13 @@ export const FontEditorToolDef: ToolDef = {
|
||||
<md-slider id="ft-ll" min="-50" max="200" value="0" step="1"></md-slider>
|
||||
</div>
|
||||
|
||||
<div class="ft-preview" id="ft-preview-box">
|
||||
<div class="ft-preview">
|
||||
<div class="ft-preview-label">
|
||||
实时预览(点击可自定义文本)
|
||||
<md-icon class="ft-preview-edit">edit</md-icon>
|
||||
</div>
|
||||
<div class="ft-preview-text" id="ft-preview"></div>
|
||||
<canvas id="ft-preview-canvas" class="ft-preview-canvas"></canvas>
|
||||
<div class="ft-preview-text" id="ft-preview" hidden></div>
|
||||
</div>
|
||||
|
||||
<md-filled-button id="ft-export-btn" class="ft-export-btn" disabled>导出字体</md-filled-button>
|
||||
|
||||
Reference in new issue
Block a user