opentypejs / opentype.js

Read and write OpenType fonts using JavaScript.
https://opentype.js.org/
MIT License
4.38k stars 468 forks source link

how to convert font's glyphs to svg or png ? #492

Closed pkjy closed 2 years ago

pkjy commented 2 years ago

I find the ttf file has 13 glyphs ,which is the same both in opentype.js and other ttf editor software (eg. FontCreator).

Glyph Inspector Glyph Inspector

FontCreator

I just tried these code , but the svg path seems not display the same as what I thought

var buffer = require('fs').readFileSync('./font.ttf')
const result = opentype.parse(buffer.buffer)
for (let key in result.glyphs.glyphs) {
  let item = result.glyphs.glyphs[key]
  if (!item.unicode) {
  } else { 
    const glyphPath = item.getPath(0, 0)
    const { x1, x2, y1, y2 } = glyphPath.getBoundingBox();
    const w = x2 - x1;
    const h = y2 - y1;
    console.log('glyphPath.getBoundingBox();', item.xMin, item.xMax, item.yMin, item.yMax, glyphPath.getBoundingBox(),getContours)
    const svgDocument = `<svg width="${w}" height="${h}" viewBox="${x1} ${y1} ${w} ${h}">
  ${glyphPath.toSVG(0)}
</svg>`;
    console.log('toSVG', svgDocument)  // here the svg result seems not the same as what I see in the FontCreator 
  }
}

for the last glyph(index12 and gplyph name uniE346 ) I get the svg <svg width="49.4296875" height="71.9296875" viewBox="3.7265625 -57.09375 49.4296875 71.9296875"> <path d="M28-50L28-50Q22-50 19-47Q15-43 15-38Q15-33 19-30Q22-26 28-26Q35-26 38-30Q42-33 42-38Q42-43 38-47Q35-50 28-50ZM28-19L28-19Q21-19 17-15Q12-12 12-6Q12 0 17 4Q21 8 28 8L28 8Q32 8 35 7Q38 6 40 4Q42 2 43-0Q45-3 45-6Q45-9 43-11Q42-14 40-15Q38-17 35-18Q32-19 28-19ZM28-57L28-57Q33-57 37-56Q41-54 44-52Q47-50 49-46Q50-43 50-39 L50-39Q50-33 47-29Q44-25 39-23L39-23L39-23L40-22Q46-21 49-17L49-17Q53-12 53-5L53-5Q53-1 51 3Q50 7 46 9Q43 12 39 13Q34 15 28 15Q23 15 18 13Q14 12 11 9Q7 7 6 3Q4-1 4- 5L4-5Q4-12 8-17Q11-21 18-23L18-23L18-23L17-24Q12-25 10-29L10-29Q7-33 7-39L7-39Q7-43 8-46Q10-49 13-52Q16-54 20-56Q24-57 28-57Z"/> </svg> when I preview this svg online svg_preview_online and it looks very strange. image

I found it's display very well in gplyph-inspector rendering by canvas .And I compare the contours and it's totally the same. so how to get right rendering by svg?

font download link: font.ttf

Your Environment

yne commented 2 years ago

There is a syntax error at the end of the SVG :

... 4- 5L4 ...

shall be

... 4-5L4 ...

since - 5 is not a valid number syntax

Are you sure OpenType.js generated this error ?

The number is serialized here: https://github.com/opentypejs/opentype.js/blob/88f7c1755ceec3326cdac4de53bc5ec89d38a615/src/path.js#L239

And I don't think either Math.round nor Number.toFixed can produce this kind of syntax error.

yne commented 2 years ago

Closing as it is not related to OpenType.js