Skip to content

Commit a4901cb

Browse files
committed
feat(font-sharp): 抽离绘图插件
1 parent cbc335c commit a4901cb

10 files changed

+229
-0
lines changed

packages/font-sharp/.babelrc

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"presets": [["@babel/preset-typescript"]]
3+
}

packages/font-sharp/.npmignore

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
temp
2+
.rollup.cache

packages/font-sharp/README.md

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Font To SVG Render
2+
3+
一个基于 Harfbuzz 的 SVG 字体渲染工具。

packages/font-sharp/package.json

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
{
2+
"name": "font-sharp",
3+
"version": "4.11.3",
4+
"description": "font to SVG Render.",
5+
"main": "dist/font-sharp/src/index.js",
6+
"type": "module",
7+
"repository": {
8+
"type": "git",
9+
"url": "https://github.com/KonghaYao/cn-font-split/tree/ts/packages/font-sharp"
10+
},
11+
"scripts": {
12+
"prepublish": "rm -r dist && tsc"
13+
},
14+
"keywords": [
15+
"font",
16+
"converter",
17+
"performance",
18+
"wasm",
19+
"woff2",
20+
"ttf",
21+
"otf",
22+
"opentype-fonts",
23+
"font-subsetter",
24+
"font-subset"
25+
],
26+
"author": "KonghaYao<[email protected]>",
27+
"license": "Apache-2.0",
28+
"peerDependencies": {
29+
"@konghayao/harfbuzzjs": "^8"
30+
},
31+
"devDependencies": {
32+
"@rollup/plugin-terser": "^0.4.4"
33+
}
34+
}

packages/font-sharp/src/font2svg.ts

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { hbjs } from '../../subsets/src/hb.js';
2+
import fs from 'fs';
3+
import { Font2SVGOptions, makeImage } from './makeImage.js';
4+
import { createRequire } from 'module';
5+
import { fileURLToPath } from 'url';
6+
import path from 'path';
7+
8+
const __filename = fileURLToPath(import.meta.url);
9+
const __dirname = path.dirname(__filename);
10+
11+
const buf = fs.readFileSync(
12+
createRequire(path.resolve(__dirname)).resolve(
13+
'@konghayao/harfbuzzjs/hb.wasm',
14+
),
15+
);
16+
const wasm = WebAssembly.instantiate(buf);
17+
18+
export const font2svg = async (
19+
ttfFile: Uint8Array,
20+
text: string,
21+
options?: Font2SVGOptions,
22+
) => {
23+
if (!wasm) throw new Error('启动 harfbuzz 失败');
24+
const hb = hbjs((await wasm).instance);
25+
const blob = hb.createBlob(ttfFile);
26+
const face = hb.createFace(blob, 0);
27+
blob.destroy();
28+
const font = hb.createFont(face);
29+
return makeImage(hb, font, text, options);
30+
};

packages/font-sharp/src/index.ts

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export * from './font2svg.js';
2+
export * from './makeImage.js';

packages/font-sharp/src/makeImage.ts

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import type { HB } from '../../subsets/src/hb.js';
2+
function shape(
3+
hb: HB.Handle,
4+
font: HB.Font,
5+
text: string,
6+
options: Font2SVGOptions,
7+
) {
8+
font.setScale(100, -100);
9+
10+
const buffer = hb.createBuffer();
11+
buffer.addText(text);
12+
buffer.guessSegmentProperties();
13+
buffer.setDirection(options.direction ?? 'ltr');
14+
hb.shape(font, buffer);
15+
const result = buffer.json();
16+
const glyphs = result.map(function (x) {
17+
return { ...x, glyph: font.glyphToPath(x.g) };
18+
});
19+
20+
buffer.destroy();
21+
return glyphs;
22+
}
23+
24+
export interface Font2SVGOptions {
25+
baseLine?: number;
26+
lineHeight?: number;
27+
direction?: 'ltr' | 'rtl' | 'ttb' | 'btt';
28+
}
29+
30+
/** render harfbuzz info to svg */
31+
export const makeImage = (
32+
hb: HB.Handle,
33+
font: HB.Font,
34+
input = '中文网字计划\nThe Project For Web',
35+
options: Font2SVGOptions = {},
36+
) => {
37+
const { baseLine = 24, lineHeight = 1 } = options;
38+
const path = input
39+
.split('\n')
40+
.map((t) => shape(hb, font, t, options))
41+
.reduce((col, cur) => {
42+
col.push(
43+
...cur,
44+
/** @ts-ignore 换行标识 */
45+
{ g: 0, glyph: undefined } as unknown as any,
46+
);
47+
return col;
48+
}, []);
49+
const lineHeightPx = 100 * lineHeight;
50+
/** 每一行相关的大小 */
51+
const bounding = { height: lineHeightPx, width: 0 };
52+
/** 画布大小 */
53+
const maxBounding = { height: 0, width: 0 };
54+
const paths = path.map((i, index) => {
55+
if (i.glyph === undefined) {
56+
bounding.height += lineHeightPx;
57+
bounding.width = 0;
58+
maxBounding.height = Math.max(maxBounding.height, bounding.height);
59+
maxBounding.width = Math.max(maxBounding.width, bounding.width);
60+
return;
61+
}
62+
const path = `<path transform="translate(${i.dx + bounding.width} ${
63+
bounding.height + i.dy
64+
})" d="${i.glyph}"></path>`;
65+
bounding.width += i.ax;
66+
maxBounding.width = Math.max(maxBounding.width, bounding.width);
67+
return path;
68+
});
69+
return `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${
70+
maxBounding.width
71+
}" height="${maxBounding.height}" viewBox="${0} ${0} ${
72+
maxBounding.width + baseLine
73+
} ${maxBounding.height + baseLine}">${paths.join('')}</svg>`;
74+
};

packages/font-sharp/test/index.mjs

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import fs from 'fs'
2+
import { font2svg } from '..'
3+
4+
const ttfFile = fs.readFileSync('../demo/public/SmileySans-Oblique.ttf')
5+
const svg = await font2svg(new Uint8Array(ttfFile))
6+
fs.writeFileSync('./temp.svg', svg)

packages/font-sharp/tsconfig.json

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
{
2+
"compilerOptions": {
3+
/* Visit https://aka.ms/tsconfig.json to read more about this file */
4+
5+
/* Basic Options */
6+
"incremental": true /* Enable incremental compilation */,
7+
"target": "ESNext" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
8+
"module": "NodeNext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
9+
// "resolveJsonModule": true,
10+
// "allowJs": true, /* Allow javascript files to be compiled. */
11+
// "checkJs": true, /* Report errors in .js files. */
12+
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
13+
"emitDeclarationOnly": false,
14+
"declaration": true /* Generates corresponding '.d.ts' file. */,
15+
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
16+
// "sourceMap": true, /* Generates corresponding '.map' file. */
17+
// "outFile": "./dist/index" /* Concatenate and emit output to single file. */,
18+
"outDir": "./dist" /* Redirect output structure to the directory. */,
19+
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
20+
// "composite": true, /* Enable project compilation */
21+
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
22+
// "removeComments": true, /* Do not emit comments to output. */
23+
// "noEmit": true, /* Do not emit outputs. */
24+
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
25+
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
26+
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
27+
28+
/* Strict Type-Checking Options */
29+
"strict": true /* Enable all strict type-checking options. */,
30+
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
31+
// "strictNullChecks": true, /* Enable strict null checks. */
32+
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
33+
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
34+
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
35+
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
36+
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
37+
38+
/* Additional Checks */
39+
// "noUnusedLocals": true, /* Report errors on unused locals. */
40+
// "noUnusedParameters": true, /* Report errors on unused parameters. */
41+
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
42+
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
43+
44+
/* Module Resolution Options */
45+
"moduleResolution": "NodeNext" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
46+
"baseUrl": "./" /* Base directory to resolve non-absolute module names. */,
47+
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
48+
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
49+
// "typeRoots": [
50+
// "@types/node"
51+
// ] /* List of folders to include type definitions from. */,
52+
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
53+
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
54+
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
55+
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
56+
57+
// "types": ["./src/env", "./src/global"],
58+
59+
/* Source Map Options */
60+
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
61+
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
62+
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
63+
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
64+
65+
/* Experimental Options */
66+
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
67+
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
68+
69+
/* Advanced Options */
70+
"skipLibCheck": true /* Skip type checking of declaration files. */,
71+
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
72+
},
73+
"include": ["src/*.ts"],
74+
"exclude": ["*.spec.ts", "../subsets/**/*"]
75+
}
File renamed without changes.

0 commit comments

Comments
 (0)