Frage

For given font, and given string, how to get polygon points like these in the picture below, in JavaScript?

alt text

(I am aware of related questions on SO, but they are for Python or other languages/environments; I would like JavaScript only solution, if possible)

EDIT: Following up @Roman's the answer:

Using typeface.js online tool, I converted a TrueType font to typeface.js format. Each letter is represented similar to this: (here is representation of letter d)

    "d": {
        "x_min": 135.640625,
        "x_max": 792.171875,
        "ha": 928,
        "o": "m 135 998 l 330 998 q 792 499 763 933 q 330 0 763 65 l 135 0 l 135 998 m 330 151 q 648 499 635 211 q 330 846 635 786 l 287 846 l 287 151 l 330 151 "
    },

The key part of typeface.js code for rendering a letter based on this format is:

switch(action) {
    case 'm':
        ctx.moveTo(outline[i++], outline[i++]);
        break;
    case 'l':
        ctx.lineTo(outline[i++], outline[i++]);
        break;
    case 'q':
        var cpx = outline[i++];
        var cpy = outline[i++];
        ctx.quadraticCurveTo(outline[i++], outline[i++], cpx, cpy);
        break;
    case 'b':
        var x = outline[i++];
        var y = outline[i++];
        ctx.bezierCurveTo(outline[i++], outline[i++], outline[i++], outline[i++], x, y);
        break;
}
War es hilfreich?

Lösung

Some work has already been done for typeface.js, a javascript library that replaces regular text with "canvas rendered one" (so you can use arbitrary font-faces).

typeface.js accomplishes this by using font definition data, which essentially holds the drawing instructions for each glyph. The data for the glyph "A" might look like this:

m 253 638 l 379 949 q 394 945 387 946 q 409 944 401 944 q 443 949 428 944 
q 565 629 525 733 q 673 359 605 526 q 822 0 740 192 q 773 3 804 0 q 736 7 
743 7 q 686 4 709 7 q 650 0 664 1 q 588 199 609 137 q 532 355 567 261 l 
370 355 l 210 355 l 159 205 q 127 110 142 161 q 99 0 112 59 l 43 6 q 6 3 
20 6 q -14 0 -8 0 q 74 211 29 105 q 155 403 119 317 q 253 638 191 490 m 
370 422 l 502 422 l 371 760 l 240 422 l 370 422

(I inserted newlines).

This string is a sequence of drawing operations with their respective numerical parameters. For example "m 253 638" corresponds to "move to x:253 y:638" and "l 379 949" being "draw line to x:379 y:949". etc, etc..

You should have a look at the source here: http://bazaar.launchpad.net/~davidchester/typeface.js/trunk/view/head:/js/typeface.js

You could adapt that renderer to extract your poligons. The major trick here is to let this page do the hard work for you and create the font definitions.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top