@7revor/opentype.js 中文文档教程
opentype.js ·
opentype.js 是 TrueType 和 OpenType 字体的 JavaScript 解析器和编写器。
它使您可以从浏览器或 Node.js 访问文本的字母形式。 有关现场演示,请参阅 https://opentype.js.org/。
Features
- Create a bézier path out of a piece of text.
- Support for composite glyphs (accented letters).
- Support for WOFF, OTF, TTF (both with TrueType
glyf
and PostScriptcff
outlines) - Support for kerning (Using GPOS or the kern table).
- Support for ligatures.
- Support for TrueType font hinting.
- Support arabic text rendering (See issue #364 & PR #359 #361)
- A low memory mode is available as an option (see #329)
- Runs in the browser and Node.js.
Installation
Using npm package manager
npm install opentype.js
const opentype = require('opentype.js');
import opentype from 'opentype.js'
import { load } from 'opentype.js'
使用打字稿? 查看此示例
注意:OpenType.js 使用 ES6 样式导入,因此如果您想在 Node.js 中编辑和调试它,请运行 npm run build< /code> 并使用
npm run watch
在文件更改时自动重建。
Directly
下载最新的 ZIP 并获取 dist
中的文件 文件夹。 这些是编的。
Using via a CDN
要通过 CDN 使用,请在您的 html 中包含以下代码:
<script src="https://cdn.jsdelivr.net/npm/opentype.js@latest/dist/opentype.min.js"></script>
Using Bower (Deprecated see official post)
要使用 Bower 安装,请在您的项目目录中输入以下命令:
bower install opentype.js
然后您可以将它们包含在您的脚本中,
<script src="/bower_components/opentype.js/dist/opentype.js"></script>
API
Loading a font
使用
: opentype.load(url, callback)
从 URL 加载字体。 由于此方法走出网络,因此它是异步的。 回调获取 (err, font)
,其中 font
是一个 Font
对象。 在使用字体之前检查 err
是否为 null。
opentype.load('fonts/Roboto-Black.ttf', function(err, font) {
if (err) {
alert('Font could not be loaded: ' + err);
} else {
// Now let's display it on a canvas with id "canvas"
const ctx = document.getElementById('canvas').getContext('2d');
// Construct a Path object containing the letter shapes of the given text.
// The other parameters are x, y and fontSize.
// Note that y is the position of the baseline.
const path = font.getPath('Hello, World!', 0, 150, 72);
// If you just want to draw the text you can also use font.draw(ctx, text, x, y, fontSize).
path.draw(ctx);
}
});
你也可以使用 es6 async/await
语法来加载你的字体
async function make(){
const font = await opentype.load('fonts/Roboto-Black.ttf');
const path = font.getPath('Hello, World!', 0, 150, 72);
console.log(path);
}
如果你已经有了一个 ArrayBuffer
,你可以使用 opentype.parse(buffer)
解析缓冲区。 这个方法总是 返回字体,但检查 font.supported
以查看字体是否为受支持的格式。 (字体可以标记为不受支持 如果他们有我们无法读取的编码表)。
const font = opentype.parse(myBuffer);
Loading a font synchronously (Node.js)
使用 opentype.loadSync(url)
从文件加载字体并返回 Font
对象。 如果无法解析字体,则抛出错误。 这仅适用于 Node.js。
const font = opentype.loadSync('fonts/Roboto-Black.ttf');
Writing a font
一旦你有了一个 Font
对象(通过使用 opentype.load
或从头开始创建一个新对象),你就可以编写它 作为二进制文件退出。
在浏览器中,您可以使用 Font.download()
指示浏览器下载二进制 .OTF 文件。 名字是根据 在字体名称上。
// Create the bézier paths for each of the glyphs.
// Note that the .notdef glyph is required.
const notdefGlyph = new opentype.Glyph({
name: '.notdef',
unicode: 0,
advanceWidth: 650,
path: new opentype.Path()
});
const aPath = new opentype.Path();
aPath.moveTo(100, 0);
aPath.lineTo(100, 700);
// more drawing instructions...
const aGlyph = new opentype.Glyph({
name: 'A',
unicode: 65,
advanceWidth: 650,
path: aPath
});
const glyphs = [notdefGlyph, aGlyph];
const font = new opentype.Font({
familyName: 'OpenTypeSans',
styleName: 'Medium',
unitsPerEm: 1000,
ascender: 800,
descender: -200,
glyphs: glyphs});
font.download();
如果要检查字体,请使用 font.toTables()
生成一个对象,显示映射的数据结构 直接转换为二进制值。 如果你想获得一个ArrayBuffer
,使用font.toArrayBuffer()
。
The Font object
Font 表示加载的 OpenType 字体文件。 它包含一组字形和方法,用于在绘图上下文中绘制文本,或获取表示文本的路径。
glyphs
: an indexed list of Glyph objects.unitsPerEm
: X/Y coordinates in fonts are stored as integers. This value determines the size of the grid. Common values are 2048 and 4096.ascender
: Distance from baseline of highest ascender. In font units, not pixels.descender
: Distance from baseline of lowest descender. In font units, not pixels.
Font.getPath(text, x, y, fontSize, options)
创建表示给定文本的路径。
x
: Horizontal position of the beginning of the text. (default: 0)y
: Vertical position of the baseline of the text. (default: 0)fontSize
: Size of the text in pixels (default: 72).
Options 是一个可选对象,包含:
kerning
: if true takes kerning information into account (default: true)features
: an object with OpenType feature tags as keys, and a boolean value to enable each feature. Currently only ligature features "liga" and "rlig" are supported (default: true).hinting
: if true uses TrueType font hinting if available (default: false).
注意:还有 Font.getPaths
具有相同的参数,它返回路径列表。
Font.draw(ctx, text, x, y, fontSize, options)
创建表示给定文本的路径。
ctx
: A 2D drawing context, like Canvas.x
: Horizontal position of the beginning of the text. (default: 0)y
: Vertical position of the baseline of the text. (default: 0)fontSize
: Size of the text in pixels (default: 72).
Options 是一个可选对象,包含:
kerning
: if true takes kerning information into account (default: true)features
: an object with OpenType feature tags as keys, and a boolean value to enable each feature. Currently only ligature features "liga" and "rlig" are supported (default: true).hinting
: if true uses TrueType font hinting if available (default: false).
Font.drawPoints(ctx, text, x, y, fontSize, options)
绘制文本中所有字形的点。 曲线上的点将以蓝色绘制,曲线外的点将以红色绘制。 参数与 Font.draw
相同。
Font.drawMetrics(ctx, text, x, y, fontSize, options)
画线指示文本中所有字形的重要字体尺寸。 黑线表示坐标系的原点(点 0,0)。 蓝线表示字形边界框。 绿线表示字形的前进宽度。
Font.stringToGlyphs(string)
将字符串转换为字形对象列表。 请注意,由于以下原因,字符串和字形列表之间没有严格的 1 对 1 对应关系 可能的替换,例如连字。 返回的字形列表可以大于或小于给定字符串的长度。
Font.charToGlyph(char)
将字符转换为 Glyph
对象。 如果找不到字形,则返回 null。 请注意,此函数假定给定字符和字形之间存在一对一映射; 对于复杂的脚本,情况可能并非如此。
Font.getKerningValue(leftGlyph, rightGlyph)
检索左字形(或其索引)和右字形(或其索引)之间的字距调整对 的值。 如果未找到字距对,则返回 0。在计算字形之间的间距时,字距值会添加到提前宽度中。
Font.getAdvanceWidth(text, fontSize, options)
返回文本的前进宽度。
这与 Path.getBoundingBox() 不同,例如 带后缀的空格会增加 advancewidth 但不会增加边界框 或者像书法“f”这样的悬垂字母可能有一个更大的 边界框比它的前进宽度。
这对应于 canvas2dContext.measureText(text).width
fontSize
: Size of the text in pixels (default: 72).options
: See Font.getPath
The Glyph object
字形是一个单独的标记,通常对应于一个字符。 一些字形,例如连字,是许多字符的组合。 字形是字体的基本构建块。
font
: A reference to theFont
object.name
: The glyph name (e.g. "Aring", "five")unicode
: The primary unicode value of this glyph (can beundefined
).unicodes
: The list of unicode values for this glyph (most of the time this will be 1, can also be empty).index
: The index number of the glyph.advanceWidth
: The width to advance the pen when drawing this glyph.xMin
,yMin
,xMax
,yMax
: The bounding box of the glyph.path
: The raw, unscaled path of the glyph.
Glyph.getPath(x, y, fontSize)
获取一个缩放的字形 Path 对象,我们可以在绘图上下文中绘制。
x
: Horizontal position of the glyph. (default: 0)y
: Vertical position of the baseline of the glyph. (default: 0)fontSize
: Font size in pixels (default: 72).
Glyph.getBoundingBox()
计算给定字形的未缩放路径的最小边界框。 返回包含 x1/y1/x2/y2 的 opentype.BoundingBox
对象。 如果字形没有点(例如空格字符),则所有坐标都将为零。
Glyph.draw(ctx, x, y, fontSize)
在给定的上下文中绘制字形。
ctx
: The drawing context.x
: Horizontal position of the glyph. (default: 0)y
: Vertical position of the baseline of the glyph. (default: 0)fontSize
: Font size, in pixels (default: 72).
Glyph.drawPoints(ctx, x, y, fontSize)
在给定的上下文中绘制字形的点。 曲线上的点将以蓝色绘制,曲线外的点将以红色绘制。 参数与 Glyph.draw
相同。
Glyph.drawMetrics(ctx, x, y, fontSize)
画线指示文本中所有字形的重要字体尺寸。 黑线表示坐标系的原点(点 0,0)。 蓝线表示字形边界框。 绿线表示字形的前进宽度。 参数与 Glyph.draw
相同。
The Path object
一旦有了通过 Font.getPath
或 Glyph.getPath
的路径,就可以使用它了。
commands
: The path commands. Each command is a dictionary containing a type and coordinates. See below for examples.fill
: The fill color of thePath
. Color is a string representing a CSS color. (default: 'black')stroke
: The stroke color of thePath
. Color is a string representing a CSS color. (default:null
: the path will not be stroked)strokeWidth
: The line thickness of thePath
. (default: 1, but since thestroke
is null no stroke will be drawn)
Path.draw(ctx)
在给定的 2D 上下文中绘制路径。 这使用了 Path
对象的 fill
、stroke
和 strokeWidth
属性。
ctx
: The drawing context.
Path.getBoundingBox()
计算给定路径的最小边界框。 返回包含 x1/y1/x2/y2 的 opentype.BoundingBox
对象。 如果路径为空(例如空格字符),则所有坐标都将为零。
Path.toPathData(decimalPlaces)
将 Path 转换为一串路径数据指令。 请参阅 https://www.w3.org/TR/SVG/paths.html#PathData
decimalPlaces
: The amount of decimal places for floating-point values. (default: 2)
Path.toSVG(decimalPlaces)
将路径转换为 SVG
decimalPlaces
: The amount of decimal places for floating-point values. (default: 2)
Path commands
- Move To: Move to a new position. This creates a new contour. Example:
{type: 'M', x: 100, y: 200}
- Line To: Draw a line from the previous position to the given coordinate. Example:
{type: 'L', x: 100, y: 200}
- Curve To: Draw a bézier curve from the current position to the given coordinate. Example:
{type: 'C', x1: 0, y1: 50, x2: 100, y2: 200, x: 100, y: 200}
- Quad To: Draw a quadratic bézier curve from the current position to the given coordinate. Example:
{type: 'Q', x1: 0, y1: 50, x: 100, y: 200}
- Close: Close the path. If stroked, this will draw a line from the first to the last point of the contour. Example:
{type: 'Z'}
Versioning
我们使用 SemVer 进行版本控制。
License
MIT
Thanks
我想感谢其他人的工作,没有他们就不可能有 opentype.js:
- pdf.js: for an awesome implementation of font parsing in the browser.
- FreeType: for the nitty-gritty details and filling in the gaps when the spec was incomplete.
- ttf.js: for hints about the TrueType parsing code.
- CFF-glyphlet-fonts: for a great explanation/implementation of CFF font writing.
- tiny-inflate: for WOFF decompression.
- Microsoft Typography: the go-to reference for all things OpenType.
- Adobe Compact Font Format spec and the Adobe Type 2 Charstring spec: explains the data structures and commands for the CFF glyph format.
- All contributing authors mentioned in the AUTHORS file.
opentype.js ·
opentype.js is a JavaScript parser and writer for TrueType and OpenType fonts.
It gives you access to the letterforms of text from the browser or Node.js. See https://opentype.js.org/ for a live demo.
Features
- Create a bézier path out of a piece of text.
- Support for composite glyphs (accented letters).
- Support for WOFF, OTF, TTF (both with TrueType
glyf
and PostScriptcff
outlines) - Support for kerning (Using GPOS or the kern table).
- Support for ligatures.
- Support for TrueType font hinting.
- Support arabic text rendering (See issue #364 & PR #359 #361)
- A low memory mode is available as an option (see #329)
- Runs in the browser and Node.js.
Installation
Using npm package manager
npm install opentype.js
const opentype = require('opentype.js');
import opentype from 'opentype.js'
import { load } from 'opentype.js'
Using TypeScript? See this example
Note: OpenType.js uses ES6-style imports, so if you want to edit it and debug it in Node.js run npm run build
first and use npm run watch
to automatically rebuild when files change.
Directly
Download the latest ZIP and grab the files in the dist
folder. These are compiled.
Using via a CDN
To use via a CDN, include the following code in your html:
<script src="https://cdn.jsdelivr.net/npm/opentype.js@latest/dist/opentype.min.js"></script>
Using Bower (Deprecated see official post)
To install using Bower, enter the following command in your project directory:
bower install opentype.js
You can then include them in your scripts using:
<script src="/bower_components/opentype.js/dist/opentype.js"></script>
API
Loading a font
Use opentype.load(url, callback)
to load a font from a URL. Since this method goes out the network, it is asynchronous. The callback gets (err, font)
where font
is a Font
object. Check if the err
is null before using the font.
opentype.load('fonts/Roboto-Black.ttf', function(err, font) {
if (err) {
alert('Font could not be loaded: ' + err);
} else {
// Now let's display it on a canvas with id "canvas"
const ctx = document.getElementById('canvas').getContext('2d');
// Construct a Path object containing the letter shapes of the given text.
// The other parameters are x, y and fontSize.
// Note that y is the position of the baseline.
const path = font.getPath('Hello, World!', 0, 150, 72);
// If you just want to draw the text you can also use font.draw(ctx, text, x, y, fontSize).
path.draw(ctx);
}
});
You can also use es6 async/await
syntax to load your fonts
async function make(){
const font = await opentype.load('fonts/Roboto-Black.ttf');
const path = font.getPath('Hello, World!', 0, 150, 72);
console.log(path);
}
If you already have an ArrayBuffer
, you can use opentype.parse(buffer)
to parse the buffer. This method always returns a Font, but check font.supported
to see if the font is in a supported format. (Fonts can be marked unsupported if they have encoding tables we can't read).
const font = opentype.parse(myBuffer);
Loading a font synchronously (Node.js)
Use opentype.loadSync(url)
to load a font from a file and return a Font
object. Throws an error if the font could not be parsed. This only works in Node.js.
const font = opentype.loadSync('fonts/Roboto-Black.ttf');
Writing a font
Once you have a Font
object (either by using opentype.load
or by creating a new one from scratch) you can write it back out as a binary file.
In the browser, you can use Font.download()
to instruct the browser to download a binary .OTF file. The name is based on the font name.
// Create the bézier paths for each of the glyphs.
// Note that the .notdef glyph is required.
const notdefGlyph = new opentype.Glyph({
name: '.notdef',
unicode: 0,
advanceWidth: 650,
path: new opentype.Path()
});
const aPath = new opentype.Path();
aPath.moveTo(100, 0);
aPath.lineTo(100, 700);
// more drawing instructions...
const aGlyph = new opentype.Glyph({
name: 'A',
unicode: 65,
advanceWidth: 650,
path: aPath
});
const glyphs = [notdefGlyph, aGlyph];
const font = new opentype.Font({
familyName: 'OpenTypeSans',
styleName: 'Medium',
unitsPerEm: 1000,
ascender: 800,
descender: -200,
glyphs: glyphs});
font.download();
If you want to inspect the font, use font.toTables()
to generate an object showing the data structures that map directly to binary values. If you want to get an ArrayBuffer
, use font.toArrayBuffer()
.
The Font object
A Font represents a loaded OpenType font file. It contains a set of glyphs and methods to draw text on a drawing context, or to get a path representing the text.
glyphs
: an indexed list of Glyph objects.unitsPerEm
: X/Y coordinates in fonts are stored as integers. This value determines the size of the grid. Common values are 2048 and 4096.ascender
: Distance from baseline of highest ascender. In font units, not pixels.descender
: Distance from baseline of lowest descender. In font units, not pixels.
Font.getPath(text, x, y, fontSize, options)
Create a Path that represents the given text.
x
: Horizontal position of the beginning of the text. (default: 0)y
: Vertical position of the baseline of the text. (default: 0)fontSize
: Size of the text in pixels (default: 72).
Options is an optional object containing:
kerning
: if true takes kerning information into account (default: true)features
: an object with OpenType feature tags as keys, and a boolean value to enable each feature. Currently only ligature features "liga" and "rlig" are supported (default: true).hinting
: if true uses TrueType font hinting if available (default: false).
Note: there is also Font.getPaths
with the same arguments which returns a list of Paths.
Font.draw(ctx, text, x, y, fontSize, options)
Create a Path that represents the given text.
ctx
: A 2D drawing context, like Canvas.x
: Horizontal position of the beginning of the text. (default: 0)y
: Vertical position of the baseline of the text. (default: 0)fontSize
: Size of the text in pixels (default: 72).
Options is an optional object containing:
kerning
: if true takes kerning information into account (default: true)features
: an object with OpenType feature tags as keys, and a boolean value to enable each feature. Currently only ligature features "liga" and "rlig" are supported (default: true).hinting
: if true uses TrueType font hinting if available (default: false).
Font.drawPoints(ctx, text, x, y, fontSize, options)
Draw the points of all glyphs in the text. On-curve points will be drawn in blue, off-curve points will be drawn in red. The arguments are the same as Font.draw
.
Font.drawMetrics(ctx, text, x, y, fontSize, options)
Draw lines indicating important font measurements for all glyphs in the text. Black lines indicate the origin of the coordinate system (point 0,0). Blue lines indicate the glyph bounding box. Green line indicates the advance width of the glyph.
Font.stringToGlyphs(string)
Convert the string to a list of glyph objects. Note that there is no strict 1-to-1 correspondence between the string and glyph list due to possible substitutions such as ligatures. The list of returned glyphs can be larger or smaller than the length of the given string.
Font.charToGlyph(char)
Convert the character to a Glyph
object. Returns null if the glyph could not be found. Note that this function assumes that there is a one-to-one mapping between the given character and a glyph; for complex scripts this might not be the case.
Font.getKerningValue(leftGlyph, rightGlyph)
Retrieve the value of the kerning pair between the left glyph (or its index) and the right glyph (or its index). If no kerning pair is found, return 0. The kerning value gets added to the advance width when calculating the spacing between glyphs.
Font.getAdvanceWidth(text, fontSize, options)
Returns the advance width of a text.
This is something different than Path.getBoundingBox() as for example a suffixed whitespace increases the advancewidth but not the bounding box or an overhanging letter like a calligraphic 'f' might have a quite larger bounding box than its advance width.
This corresponds to canvas2dContext.measureText(text).width
fontSize
: Size of the text in pixels (default: 72).options
: See Font.getPath
The Glyph object
A Glyph is an individual mark that often corresponds to a character. Some glyphs, such as ligatures, are a combination of many characters. Glyphs are the basic building blocks of a font.
font
: A reference to theFont
object.name
: The glyph name (e.g. "Aring", "five")unicode
: The primary unicode value of this glyph (can beundefined
).unicodes
: The list of unicode values for this glyph (most of the time this will be 1, can also be empty).index
: The index number of the glyph.advanceWidth
: The width to advance the pen when drawing this glyph.xMin
,yMin
,xMax
,yMax
: The bounding box of the glyph.path
: The raw, unscaled path of the glyph.
Glyph.getPath(x, y, fontSize)
Get a scaled glyph Path object we can draw on a drawing context.
x
: Horizontal position of the glyph. (default: 0)y
: Vertical position of the baseline of the glyph. (default: 0)fontSize
: Font size in pixels (default: 72).
Glyph.getBoundingBox()
Calculate the minimum bounding box for the unscaled path of the given glyph. Returns an opentype.BoundingBox
object that contains x1/y1/x2/y2. If the glyph has no points (e.g. a space character), all coordinates will be zero.
Glyph.draw(ctx, x, y, fontSize)
Draw the glyph on the given context.
ctx
: The drawing context.x
: Horizontal position of the glyph. (default: 0)y
: Vertical position of the baseline of the glyph. (default: 0)fontSize
: Font size, in pixels (default: 72).
Glyph.drawPoints(ctx, x, y, fontSize)
Draw the points of the glyph on the given context. On-curve points will be drawn in blue, off-curve points will be drawn in red. The arguments are the same as Glyph.draw
.
Glyph.drawMetrics(ctx, x, y, fontSize)
Draw lines indicating important font measurements for all glyphs in the text. Black lines indicate the origin of the coordinate system (point 0,0). Blue lines indicate the glyph bounding box. Green line indicates the advance width of the glyph. The arguments are the same as Glyph.draw
.
The Path object
Once you have a path through Font.getPath
or Glyph.getPath
, you can use it.
commands
: The path commands. Each command is a dictionary containing a type and coordinates. See below for examples.fill
: The fill color of thePath
. Color is a string representing a CSS color. (default: 'black')stroke
: The stroke color of thePath
. Color is a string representing a CSS color. (default:null
: the path will not be stroked)strokeWidth
: The line thickness of thePath
. (default: 1, but since thestroke
is null no stroke will be drawn)
Path.draw(ctx)
Draw the path on the given 2D context. This uses the fill
, stroke
and strokeWidth
properties of the Path
object.
ctx
: The drawing context.
Path.getBoundingBox()
Calculate the minimum bounding box for the given path. Returns an opentype.BoundingBox
object that contains x1/y1/x2/y2. If the path is empty (e.g. a space character), all coordinates will be zero.
Path.toPathData(decimalPlaces)
Convert the Path to a string of path data instructions. See https://www.w3.org/TR/SVG/paths.html#PathData
decimalPlaces
: The amount of decimal places for floating-point values. (default: 2)
Path.toSVG(decimalPlaces)
Convert the path to a SVG <path> element, as a string.
decimalPlaces
: The amount of decimal places for floating-point values. (default: 2)
Path commands
- Move To: Move to a new position. This creates a new contour. Example:
{type: 'M', x: 100, y: 200}
- Line To: Draw a line from the previous position to the given coordinate. Example:
{type: 'L', x: 100, y: 200}
- Curve To: Draw a bézier curve from the current position to the given coordinate. Example:
{type: 'C', x1: 0, y1: 50, x2: 100, y2: 200, x: 100, y: 200}
- Quad To: Draw a quadratic bézier curve from the current position to the given coordinate. Example:
{type: 'Q', x1: 0, y1: 50, x: 100, y: 200}
- Close: Close the path. If stroked, this will draw a line from the first to the last point of the contour. Example:
{type: 'Z'}
Versioning
We use SemVer for versioning.
License
MIT
Thanks
I would like to acknowledge the work of others without which opentype.js wouldn't be possible:
- pdf.js: for an awesome implementation of font parsing in the browser.
- FreeType: for the nitty-gritty details and filling in the gaps when the spec was incomplete.
- ttf.js: for hints about the TrueType parsing code.
- CFF-glyphlet-fonts: for a great explanation/implementation of CFF font writing.
- tiny-inflate: for WOFF decompression.
- Microsoft Typography: the go-to reference for all things OpenType.
- Adobe Compact Font Format spec and the Adobe Type 2 Charstring spec: explains the data structures and commands for the CFF glyph format.
- All contributing authors mentioned in the AUTHORS file.