mikolalysenko / vectorize-text

Turns a text string into a 2D poly line
MIT License
307 stars 21 forks source link

vectorize-text

Convert a string of text into a vectorized geometric representation. Works in both node.js and browserify.

Example

This module is capable of outputting geometry in several formats.

Planar graphs

The default (and fastest) output from the module is a planar graph:

var vectorizeText = require("vectorize-text")

var graph = vectorizeText("Hello world! 你好", {
  width: 500,
  textBaseline: "hanging"
})

var svg = ['<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"  width="500"  height="80" >']
graph.edges.forEach(function(e) {
  var p0 = graph.positions[e[0]]
  var p1 = graph.positions[e[1]]
  svg.push('<line x1="' + p0[0] + '" y1="' + p0[1] +
    '" x2="' + p1[0] + '" y2="' + p1[1] +
    '" stroke-width="1" stroke="black" />')
})
svg.push("</svg>")

console.log(svg.join(""))

Output:

Polygons

You can also configure the module to emit polygons instead:

var vectorizeText = require("vectorize-text")

var polygons = vectorizeText("Hello world! 你好", {
  polygons: true,
  width: 500,
  textBaseline: "hanging"
})

var svg = []
svg.push('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"  width="500"  height="80" >')
polygons.forEach(function(loops) {
  svg.push('<path d="')
  loops.forEach(function(loop) {
    var start = loop[0]
    svg.push('M ' + start[0] + ' ' + start[1])
    for(var i=1; i<loop.length; ++i) {
      var p = loop[i]
      svg.push('L ' + p[0] + ' ' + p[1])
    }
    svg.push('L ' + start[0] + ' ' + start[1])
  })
  svg.push('" fill-rule="even-odd" stroke-width="1" fill="red"></path>')
})
svg.push('</svg>')

console.log(svg)

Output:

Triangulations

Finally, the module can output a triangulation (which is compatible with WebGL for example):

var vectorizeText = require("vectorize-text")

var complex = vectorizeText("Hello world! 你好", {
  triangles: true,
  width: 500,
  textBaseline: "hanging"
})

var svg = ['<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"  width="500"  height="80" >']
complex.cells.forEach(function(c) {
  for(var j=0; j<3; ++j) {
    var p0 = complex.positions[c[j]]
    var p1 = complex.positions[c[(j+1)%3]]
    svg.push('<line x1="' + p0[0] + '" y1="' + p0[1] +
      '" x2="' + p1[0] + '" y2="' + p1[1] +
      '" stroke-width="1" stroke="black" />')
  }
})
svg.push("</svg>")

console.log(svg)

Output:

Install

npm install vectorize-text

API

require("vectorize-text")(string[,options])

Renders a string to a 2D cell complex

Returns The returned value depends on the type of geometry

Note In node.js, this library requires Cairo. For more information on how to set this up, look at the documentation for the canvas module.

Credits

(c) 2014 Mikola Lysenko. MIT License