如何使用JavaScript将字母的字形轮廓作为bézier路径? [英] How do I get glyph outlines of a letter as bézier paths using JavaScript?

查看:244
本文介绍了如何使用JavaScript将字母的字形轮廓作为bézier路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在HTML5中检索字体字形的轮廓信息作为bézier路径。这将允许我随机化轮廓:



在Cocoa中,我会使用有一个实例。


I want to retrieve the outline information of font glyphs as bézier paths in HTML5. This would allow me to randomize the outlines:

In Cocoa, I would use appendBezierPathWithGlyph:inFont:. In Java, I would use TextLayout.getOutline(). How does this work in JavaScript?

I discovered that Mozilla has mozPathText but I can't get it to work.

解决方案

Out of necessity I've created my own library called opentype.js. It parses OpenType and TrueType fonts. PostScript and WOFF will be supported in the future.

Here's how it parses a typeface:

  • Load the .ttf / .otf file using a XMLHttpRequest.
  • Parse the glyf and loca table to extract the letter shapes (glyphs).
  • Parse the cname table which contains the mapping from characters to glyphs.
  • Parse the head and hmtx table to get the metrics, basically the spacing between each letter.

Then it can create a bézier path:

  • Convert the letters of the text into glyphs.
  • Convert the coordinates of the glyph to quadratic curves.
  • Adjust the spacing using kerning information.

This results in a path that you can draw using the HTML5 canvas:

var font = opentype.parseFont(arrayBuffer);
var path = font.getPath("Hello, World!", {x:0, y:150, fontSize:72});
path.draw(ctx);

The demo website has a live example.

这篇关于如何使用JavaScript将字母的字形轮廓作为bézier路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆