Skip to content

Commit

Permalink
feat(font-sharp): 抽离绘图插件
Browse files Browse the repository at this point in the history
  • Loading branch information
KonghaYao committed Mar 23, 2024
1 parent cbc335c commit a4901cb
Show file tree
Hide file tree
Showing 10 changed files with 229 additions and 0 deletions.
3 changes: 3 additions & 0 deletions packages/font-sharp/.babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"presets": [["@babel/preset-typescript"]]
}
2 changes: 2 additions & 0 deletions packages/font-sharp/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
temp
.rollup.cache
3 changes: 3 additions & 0 deletions packages/font-sharp/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Font To SVG Render

一个基于 Harfbuzz 的 SVG 字体渲染工具。
34 changes: 34 additions & 0 deletions packages/font-sharp/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "font-sharp",
"version": "4.11.3",
"description": "font to SVG Render.",
"main": "dist/font-sharp/src/index.js",
"type": "module",
"repository": {
"type": "git",
"url": "https://github.com/KonghaYao/cn-font-split/tree/ts/packages/font-sharp"
},
"scripts": {
"prepublish": "rm -r dist && tsc"
},
"keywords": [
"font",
"converter",
"performance",
"wasm",
"woff2",
"ttf",
"otf",
"opentype-fonts",
"font-subsetter",
"font-subset"
],
"author": "KonghaYao<[email protected]>",
"license": "Apache-2.0",
"peerDependencies": {
"@konghayao/harfbuzzjs": "^8"
},
"devDependencies": {
"@rollup/plugin-terser": "^0.4.4"
}
}
30 changes: 30 additions & 0 deletions packages/font-sharp/src/font2svg.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { hbjs } from '../../subsets/src/hb.js';
import fs from 'fs';
import { Font2SVGOptions, makeImage } from './makeImage.js';
import { createRequire } from 'module';
import { fileURLToPath } from 'url';
import path from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const buf = fs.readFileSync(
createRequire(path.resolve(__dirname)).resolve(
'@konghayao/harfbuzzjs/hb.wasm',
),
);
const wasm = WebAssembly.instantiate(buf);

export const font2svg = async (
ttfFile: Uint8Array,
text: string,
options?: Font2SVGOptions,
) => {
if (!wasm) throw new Error('启动 harfbuzz 失败');
const hb = hbjs((await wasm).instance);
const blob = hb.createBlob(ttfFile);
const face = hb.createFace(blob, 0);
blob.destroy();
const font = hb.createFont(face);
return makeImage(hb, font, text, options);
};
2 changes: 2 additions & 0 deletions packages/font-sharp/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './font2svg.js';
export * from './makeImage.js';
74 changes: 74 additions & 0 deletions packages/font-sharp/src/makeImage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import type { HB } from '../../subsets/src/hb.js';
function shape(
hb: HB.Handle,
font: HB.Font,
text: string,
options: Font2SVGOptions,
) {
font.setScale(100, -100);

const buffer = hb.createBuffer();
buffer.addText(text);
buffer.guessSegmentProperties();
buffer.setDirection(options.direction ?? 'ltr');
hb.shape(font, buffer);
const result = buffer.json();
const glyphs = result.map(function (x) {
return { ...x, glyph: font.glyphToPath(x.g) };
});

buffer.destroy();
return glyphs;
}

export interface Font2SVGOptions {
baseLine?: number;
lineHeight?: number;
direction?: 'ltr' | 'rtl' | 'ttb' | 'btt';
}

/** render harfbuzz info to svg */
export const makeImage = (
hb: HB.Handle,
font: HB.Font,
input = '中文网字计划\nThe Project For Web',
options: Font2SVGOptions = {},
) => {
const { baseLine = 24, lineHeight = 1 } = options;
const path = input
.split('\n')
.map((t) => shape(hb, font, t, options))
.reduce((col, cur) => {
col.push(
...cur,
/** @ts-ignore 换行标识 */
{ g: 0, glyph: undefined } as unknown as any,
);
return col;
}, []);
const lineHeightPx = 100 * lineHeight;
/** 每一行相关的大小 */
const bounding = { height: lineHeightPx, width: 0 };
/** 画布大小 */
const maxBounding = { height: 0, width: 0 };
const paths = path.map((i, index) => {
if (i.glyph === undefined) {
bounding.height += lineHeightPx;
bounding.width = 0;
maxBounding.height = Math.max(maxBounding.height, bounding.height);
maxBounding.width = Math.max(maxBounding.width, bounding.width);
return;
}
const path = `<path transform="translate(${i.dx + bounding.width} ${
bounding.height + i.dy
})" d="${i.glyph}"></path>`;
bounding.width += i.ax;
maxBounding.width = Math.max(maxBounding.width, bounding.width);
return path;
});
return `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${
maxBounding.width
}" height="${maxBounding.height}" viewBox="${0} ${0} ${
maxBounding.width + baseLine
} ${maxBounding.height + baseLine}">${paths.join('')}</svg>`;
};
6 changes: 6 additions & 0 deletions packages/font-sharp/test/index.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import fs from 'fs'
import { font2svg } from '..'

const ttfFile = fs.readFileSync('../demo/public/SmileySans-Oblique.ttf')
const svg = await font2svg(new Uint8Array(ttfFile))
fs.writeFileSync('./temp.svg', svg)
75 changes: 75 additions & 0 deletions packages/font-sharp/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */

/* Basic Options */
"incremental": true /* Enable incremental compilation */,
"target": "ESNext" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
"module": "NodeNext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
// "resolveJsonModule": true,
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"emitDeclarationOnly": false,
"declaration": true /* Generates corresponding '.d.ts' file. */,
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./dist/index" /* Concatenate and emit output to single file. */,
"outDir": "./dist" /* Redirect output structure to the directory. */,
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */

/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */

/* Module Resolution Options */
"moduleResolution": "NodeNext" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
"baseUrl": "./" /* Base directory to resolve non-absolute module names. */,
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [
// "@types/node"
// ] /* List of folders to include type definitions from. */,
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */

// "types": ["./src/env", "./src/global"],

/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */

/* Advanced Options */
"skipLibCheck": true /* Skip type checking of declaration files. */,
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"include": ["src/*.ts"],
"exclude": ["*.spec.ts", "../subsets/**/*"]
}
File renamed without changes.

0 comments on commit a4901cb

Please sign in to comment.