Skip to content
Blazingly fast measure string width in pixels on the server in Javascript (Node.Js)
Branch: master
Clone or download
Latest commit 8bf5e90 Jan 9, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
__tests__ fixed failing test, added test for Tahoma, added Tahoma to ReadMe Feb 11, 2018
docs Added contribution guide. Aug 4, 2017
src
.babelrc
.eslintrc
.gitignore Initial commit Jan 3, 2017
.npmignore Initial commit Jan 3, 2017
.travis.yml Update .travis.yml Feb 12, 2018
README.md Add Helvetica to readme Jan 9, 2019
gulpfile.babel.js Initial commit Jan 3, 2017
package.json
yarn.lock committed yarn.lock Jan 9, 2019

README.md

string-pixel-width

Build Status npm version Coverage Status

String pixel width measurement on the backend in Javascript.

Why I created this package? Read more about purpose

Installation

To install the stable version:

npm install --save string-pixel-width

Supported fonts:

  • Andale Mono
  • Arial
  • Avenir
  • Avenir Next
  • Comic Sans MS
  • Courier New
  • Georgia
  • Helvetica
  • Impact
  • Times New Roman
  • Trebuchet MS
  • Verdana
  • Webdings
  • Open Sans
  • Tahoma

Example

var pixelWidth = require('string-pixel-width');

const width = pixelWidth('My text ...', { size: 10 });
console.log('This text is ' + width + 'px long in the size of 10px.');

// This text is 43.5px long in the size of 10px.
var pixelWidth = require('string-pixel-width');

const width = pixelWidth('My text ...', { font: 'impact', size: 10 });
console.log('This text is ' + width + 'px long in the size of 10px.');

// This text is 42px long in the size of 10px.
var pixelWidth = require('string-pixel-width');

const width = pixelWidth('My text ...', { font: 'open sans', size: 10, bold: true, italic: true });
console.log('This text is ' + width + 'px long in the size of 10px.');

// This text is 47px long in the size of 10px using bold and italic proportions.

How to contribute

PRs are welcome :) This library uses static map of width of every ASCII letter for all supported fonts.

  1. Clone the repository
  2. Open file src/pixelWidthCalculator.html in your editor
  3. Add your font name into array of fonts (currently var websafe) and save
  4. Open up src/pixelWidthCalculator.html in Google Chrome. It should look like this: PHPStan
  5. Map of withs will be generated for you - copy it and replace content of file src/widthsMap.js

Please everytime make sure you don't broke existing fonts - remove any font or broke his widths.

You can’t perform that action at this time.