ch-to-path.js 960 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. const assert = require('assert');
  3. function rndPathCmd(cmd) {
  4. const r = (Math.random() * 0.2) - 0.1;
  5. switch (cmd.type) {
  6. case 'M': case 'L':
  7. cmd.x += r;
  8. cmd.y += r;
  9. break;
  10. case 'Q': case 'C':
  11. cmd.x += r;
  12. cmd.y += r;
  13. cmd.x1 += r;
  14. cmd.y1 += r;
  15. break;
  16. default:
  17. // Close path cmd
  18. break;
  19. }
  20. return cmd;
  21. }
  22. module.exports = function (text, opts) {
  23. const ch = text[0];
  24. assert(ch, 'expect a string');
  25. const fontSize = opts.fontSize;
  26. const fontScale = fontSize / opts.font.unitsPerEm;
  27. const glyph = opts.font.charToGlyph(ch);
  28. const width = glyph.advanceWidth ? glyph.advanceWidth * fontScale : 0;
  29. const left = opts.x - (width / 2);
  30. const height = (opts.ascender + opts.descender) * fontScale;
  31. const top = opts.y + (height / 2);
  32. const path = glyph.getPath(left, top, fontSize);
  33. // Randomize path commands
  34. path.commands.forEach(rndPathCmd);
  35. const pathData = path.toPathData();
  36. return pathData;
  37. };