opentypejs / opentype.js

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

Glyph.toSVG or Path.toSVG? #127

Closed Pomax closed 1 year ago

Pomax commented 9 years ago

Is there any API for converting glyphs or paths to SVG, instead of drawing them onto a context? Especially on the Node side of things these are relatively necessary (glyph lookup REST servers, for instance).

I can trivially implement one as

function toSVG(path) {
  return path.commands.map(function(v) { return [v.type, v.x, v.y].join(' '); }).join(' ');
}

but having it built in would be very nice, especially if it came with an option to round outline fractionals to however-many-decimal-places.

Pomax commented 9 years ago

As per https://github.com/nodebox/opentype.js/issues/128, the above function doesn't work. However, this does:

var Interpreter = function() {
  this.stack = [];
};

Interpreter.prototype = {
  beginPath: function() {},
  moveTo: function(x,y) {
    this.stack.push(["M", x, y].join(" "));
  },
  lineTo: function(x,y) {
    this.stack.push(["L", x, y].join(" "));
  },
  quadraticCurveTo: function(x1, y1, x, y) {
    this.stack.push(["Q", x1, y1, x, y].join(" "));
  },
  cubicCurveTo: function(x1, y1, x2, y2, x, y) {
    this.stack.push(["C", x1, y1, x2, y2 x, y].join(" "));
  },
  closePath: function() {
    this.stack.push("Z");
  },
  fill: function(f) {
    this.fillStyle = f;
  },
  stroke: function(s) {
    this.strokeStyle = s;
  },
  toPath: function() {
    return this.stack.join(" ");
  }
};

And then feeding that into a draw call, to draw "to string" rather than to a canvas:

var path = font.getPath(id, size*idx, size, size);
var interpreter = new Interpreter();
path.draw(interpreter);
var svgPath = interpreter.toPath();
8eecf0d2 commented 6 years ago

Additionally, if there was an API for parsing an SVG path it would enable character manipulations (alignment, scale, etc...) through SVG transformation libraries.

Path.fromSvg('M150 0 L75 200 L225 200 Z')
Jolg42 commented 6 years ago

@8eecf0d2 Indeed, for now you can use https://github.com/nfroidure/svg-pathdata and convert SVG path to commands.

rhulha commented 1 year ago

Since this library now contains a Path.toSVG(decimalPlaces) call, I think we can close this issue, or?

Pomax commented 1 year ago

if you want to mention as of which version this is supported, that should be enough to close this issue, yes.

rhulha commented 1 year ago

https://github.com/opentypejs/opentype.js/releases/tag/1.3.1

Pomax commented 1 year ago

good enough to consider it resolved. Thanks

VivaRado commented 1 year ago

@8eecf0d2 Indeed, for now you can use https://github.com/nfroidure/svg-pathdata and convert SVG path to commands.

https://gist.github.com/VivaRado/9606e9c0be095241a903dc716c7b596c