mirror of
https://github.com/2234839/web-font.git
synced 2026-11-23 06:36:37 +08:00
fix: 修复找字体预览镂空问题
This commit is contained in:
parent
8306a03efe
commit
e1579eb3cf
@ -175,33 +175,38 @@ function flattenContour(rawContour: RawContour): Pt[] {
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫描线填充多边形集合(奇偶规则),输出覆盖网格的二值位图
|
||||
* polys 顶点已是目标网格坐标系(含翻转与缩放)
|
||||
* 扫描线按非零环绕规则填充多边形集合
|
||||
* polys 顶点已是目标网格坐标系(含翻转与缩放)。
|
||||
* 必须合并全部轮廓的交点:外轮廓与内轮廓方向相反,内轮廓处的环绕数归零,
|
||||
* 从而保留「借」「日」等字形的封闭留白。
|
||||
*/
|
||||
function scanlineFill(polys: Pt[][]): Uint8Array {
|
||||
const grid = new Uint8Array(GRID * GRID);
|
||||
for (const poly of polys) {
|
||||
if (poly.length < 3) continue;
|
||||
for (let y = 0; y < GRID; y++) {
|
||||
const sy = y + 0.5;
|
||||
/** 收集该扫描线与全部边的交点 x */
|
||||
const xs: number[] = [];
|
||||
for (let y = 0; y < GRID; y++) {
|
||||
const sy = y + 0.5;
|
||||
const crossings: Array<{ x: number; winding: number }> = [];
|
||||
for (const poly of polys) {
|
||||
if (poly.length < 3) continue;
|
||||
for (let i = 0; i < poly.length; i++) {
|
||||
const a = poly[i]!;
|
||||
const b = poly[(i + 1) % poly.length]!;
|
||||
/** 水平边无交点 */
|
||||
if (a.y === b.y) continue;
|
||||
if ((sy >= a.y && sy < b.y) || (sy >= b.y && sy < a.y)) {
|
||||
xs.push(a.x + ((sy - a.y) / (b.y - a.y)) * (b.x - a.x));
|
||||
crossings.push({
|
||||
x: a.x + ((sy - a.y) / (b.y - a.y)) * (b.x - a.x),
|
||||
winding: a.y < b.y ? 1 : -1,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (xs.length < 2) continue;
|
||||
xs.sort((p, q) => p - q);
|
||||
for (let k = 0; k + 1 < xs.length; k += 2) {
|
||||
const x0 = Math.max(0, Math.ceil(xs[k]! - 0.5));
|
||||
const x1 = Math.min(GRID - 1, Math.floor(xs[k + 1]! - 0.5));
|
||||
for (let x = x0; x <= x1; x++) grid[y * GRID + x] = 1;
|
||||
}
|
||||
}
|
||||
crossings.sort((a, b) => a.x - b.x);
|
||||
let winding = 0;
|
||||
for (let i = 0; i + 1 < crossings.length; i++) {
|
||||
winding += crossings[i]!.winding;
|
||||
if (winding === 0) continue;
|
||||
const x0 = Math.max(0, Math.ceil(crossings[i]!.x - 0.5));
|
||||
const x1 = Math.min(GRID - 1, Math.floor(crossings[i + 1]!.x - 0.5));
|
||||
for (let x = x0; x <= x1; x++) grid[y * GRID + x] = 1;
|
||||
}
|
||||
}
|
||||
return grid;
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "webfont",
|
||||
"private": true,
|
||||
"version": "1.14.0",
|
||||
"version": "1.14.1",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "pnpx tsx scripts/dev-all.ts",
|
||||
|
||||
@ -18,6 +18,35 @@ import { fontDirs } from "../backend/config";
|
||||
const TARGET_FONT = "思源黑体.ttf";
|
||||
const TEXT = "天地玄黄";
|
||||
|
||||
/** 统计不与位图边缘连通的白色像素,用于验证字形内部镂空仍然存在 */
|
||||
function countEnclosedWhitePixels(bitmap: Uint8Array): number {
|
||||
const visited = new Uint8Array(bitmap.length);
|
||||
let enclosedTotal = 0;
|
||||
for (let start = 0; start < bitmap.length; start++) {
|
||||
if (bitmap[start] || visited[start]) continue;
|
||||
const stack = [start];
|
||||
visited[start] = 1;
|
||||
let size = 0;
|
||||
let enclosed = true;
|
||||
while (stack.length) {
|
||||
const index = stack.pop()!;
|
||||
const x = index % 64;
|
||||
const y = Math.floor(index / 64);
|
||||
size++;
|
||||
if (x === 0 || y === 0 || x === 63 || y === 63) enclosed = false;
|
||||
const neighbors = [index - 1, index + 1, index - 64, index + 64];
|
||||
for (const next of neighbors) {
|
||||
if (next < 0 || next >= bitmap.length || bitmap[next] || visited[next]) continue;
|
||||
if ((x === 0 && next === index - 1) || (x === 63 && next === index + 1)) continue;
|
||||
visited[next] = 1;
|
||||
stack.push(next);
|
||||
}
|
||||
}
|
||||
if (enclosed) enclosedTotal += size;
|
||||
}
|
||||
return enclosedTotal;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log("=== 服务端字形比对自测 ===");
|
||||
|
||||
@ -28,6 +57,12 @@ async function main() {
|
||||
});
|
||||
if (!ttf) throw new Error(`无法加载目标字体 ${TARGET_FONT}`);
|
||||
|
||||
/** 「借」的「日」有两个封闭留白,不能因轮廓填充错误变成实心 */
|
||||
const jieBitmap = getGlyphBitmap(ttf, TARGET_FONT, "借".codePointAt(0)!);
|
||||
const enclosed = jieBitmap ? countEnclosedWhitePixels(jieBitmap) : 0;
|
||||
console.log(` 借: 封闭留白像素=${enclosed}`);
|
||||
if (enclosed < 8) throw new Error(`${TARGET_FONT} 的「借」内部留白丢失`);
|
||||
|
||||
const queryBitmaps: Uint8Array[] = [];
|
||||
for (const ch of TEXT) {
|
||||
const cp = ch.codePointAt(0)!;
|
||||
|
||||
@ -130,6 +130,23 @@ async function loadSubsetFontFace(font: string, text: string): Promise<FontFace>
|
||||
return face;
|
||||
}
|
||||
|
||||
/** 一次裁剪指定字体所需字符,并用浏览器生成各字符的归一化预览 */
|
||||
export async function renderSubsetGlyphPreviews(font: string, chars: string[]): Promise<Map<string, string>> {
|
||||
const face = await loadSubsetFontFace(font, [...new Set(chars)].join(""));
|
||||
const previews = new Map<string, string>();
|
||||
try {
|
||||
for (const char of new Set(chars)) {
|
||||
const rawMask = renderCharMask(char, face.family, 96);
|
||||
if (rawMask) {
|
||||
previews.set(char, rgbaToDataURL(maskToNormalizedRGBA(tightCrop(rawMask))));
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
document.fonts.delete(face);
|
||||
}
|
||||
return previews;
|
||||
}
|
||||
|
||||
/**
|
||||
* 对单个候选字体执行比对
|
||||
*
|
||||
|
||||
@ -10,8 +10,7 @@
|
||||
*/
|
||||
import { ref, computed, useTemplateRef } from "vue";
|
||||
import { usePageSeo } from "../useSeo";
|
||||
import { prepareQueryGlyphs } from "../font-finder/matcher";
|
||||
import { rgbaToDataURL } from "../font-finder/segmenter";
|
||||
import { prepareQueryGlyphs, renderSubsetGlyphPreviews } from "../font-finder/matcher";
|
||||
|
||||
/** 服务端返回的单字体结果(与 backend/routes/glyph_match.ts 对齐) */
|
||||
interface ServerFontResult {
|
||||
@ -28,19 +27,6 @@ function rgbaToBitString(rgba: Uint8Array): string {
|
||||
return s;
|
||||
}
|
||||
|
||||
/** 01 串 → 灰度预览 DataURL */
|
||||
function bitStringToDataURL(bits: string): string {
|
||||
const rgba = new Uint8Array(64 * 64 * 4);
|
||||
for (let i = 0; i < bits.length; i++) {
|
||||
const v = bits[i] === "1" ? 0 : 255;
|
||||
rgba[i * 4] = v;
|
||||
rgba[i * 4 + 1] = v;
|
||||
rgba[i * 4 + 2] = v;
|
||||
rgba[i * 4 + 3] = 255;
|
||||
}
|
||||
return rgbaToDataURL(rgba);
|
||||
}
|
||||
|
||||
usePageSeo({
|
||||
title: "截图找字体 | 以图搜字体 | 在线字体识别",
|
||||
description: "上传文字截图,框选并确认文字,即可在站内字体库中查找字形最相似的字体。",
|
||||
@ -226,16 +212,10 @@ function onGlyphInput() {
|
||||
results.value = [];
|
||||
}
|
||||
|
||||
/** 服务端结果 → 展示用预览图(同字体同字只转一次) */
|
||||
/** 裁剪接口生成的字体预览缓存(同字体同字只渲染一次) */
|
||||
const glyphPreviewCache = new Map<string, string>();
|
||||
function serverGlyphPreview(font: string, char: string, bitmap: string): string {
|
||||
const key = font + "|" + char;
|
||||
let url = glyphPreviewCache.get(key);
|
||||
if (!url) {
|
||||
url = bitStringToDataURL(bitmap);
|
||||
glyphPreviewCache.set(key, url);
|
||||
}
|
||||
return url;
|
||||
function serverGlyphPreview(font: string, char: string): string {
|
||||
return glyphPreviewCache.get(font + "|" + char) ?? "";
|
||||
}
|
||||
|
||||
/** 结果中的查询序号 → 原始图块预览,留空图块与候选字体缺字均不会造成错位 */
|
||||
@ -266,7 +246,15 @@ async function startMatch() {
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const data = (await res.json()) as { results?: ServerFontResult[]; error?: string };
|
||||
if (data.error) throw new Error(data.error);
|
||||
results.value = data.results ?? [];
|
||||
const matchedResults = data.results ?? [];
|
||||
/** 每个字体只裁剪一次,同次裁剪包含该结果需要展示的全部字符 */
|
||||
await Promise.all(matchedResults.map(async (result) => {
|
||||
const previews = await renderSubsetGlyphPreviews(result.font, result.glyphs.map((g) => g.char));
|
||||
for (const [char, preview] of previews) {
|
||||
glyphPreviewCache.set(result.font + "|" + char, preview);
|
||||
}
|
||||
}));
|
||||
results.value = matchedResults;
|
||||
totalCount.value = results.value.length;
|
||||
doneCount.value = results.value.length;
|
||||
elapsedMs.value = Math.round(performance.now() - t0);
|
||||
@ -401,7 +389,7 @@ const scoreColor = (s: number) => (s > 0.9 ? "#16a34a" : s > 0.8 ? "#d97706" : "
|
||||
<div v-for="g in r.glyphs" :key="g.queryIndex" style="text-align: center">
|
||||
<div style="display: flex; gap: 2px">
|
||||
<img :src="queryPreview(g.queryIndex)" style="width: 34px; height: 34px; image-rendering: pixelated; border: 1px solid #eee; border-radius: 4px" title="截图" />
|
||||
<img :src="serverGlyphPreview(r.font, g.char, g.bitmap)" style="width: 34px; height: 34px; image-rendering: pixelated; border: 1px solid #eee; border-radius: 4px" title="该字体渲染" />
|
||||
<img :src="serverGlyphPreview(r.font, g.char)" style="width: 34px; height: 34px; image-rendering: pixelated; border: 1px solid #eee; border-radius: 4px" title="该字体渲染" />
|
||||
</div>
|
||||
<div style="font-size: 10px; color: #999; margin-top: 2px">{{ g.char }} {{ pct(g.score) }}</div>
|
||||
</div>
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user