Code Monkey home page Code Monkey logo

text-metrics's Introduction

text-metrics

NPM version Build Status BrowserStack Status Download Coverage Status

An lightweight & efficient text measurement set for the browser using canvas to prevent layout reflows.

Features

  • Compute width
  • Compute height
  • Compute linebreaks
  • Compute max font-size to fit into element

Installation

If you're using node, you can run npm install text-metrics.

text-metrics is also available via Bower (bower install text-metrics)

Alternatively if you just want to grab the file yourself, you can download either the current stable production version or the development version directly.

Setting it up

text-metrics supports AMD (e.g. RequireJS), CommonJS (e.g. Node.js) and direct usage (e.g. loading globally with a <script> tag) loading methods. You should be able to do nearly anything, and then skip to the next section anyway and have it work. Just in case though, here's some specific examples that definitely do the right thing:

CommonsJS (e.g. Node)

text-metrics needs some browser environment to run.

const textMetrics = require('text-metrics');

const el = document.querySelector('h1');
const metrics = textMetrics.init(el);

metrics.width('unicorns');
// -> 210

metrics.height('Some long text with automatic word wraparound');
// -> 180
metrics.lines('Some long text with automatic word wraparound');
// -> ['Some long text', 'with automatic', 'word', 'wraparound']
metrics.maxFontSize('Fitting Headline');
// -> 33px

Webpack / Browserify

const textMetrics = require('text-metrics');
textMetrics.init(document.querySelector('.textblock')).lines();

AMD (e.g. RequireJS)

define(['text-metrics'], function (textMetrics) {
  textMetrics.init(document.querySelector('h1')).width('unicorns');
});

Directly in your web page:

<script src="text-metrics.min.js"></script>
<script>
  textMetrics.init(document.querySelector('h1')).width('unicorns');
</script>

API

Construct textmetrics object:

textMetrics.init([el, overwrites])

You can call textMetrics with either an HTMLElement or with an object with style overwrites or with both. e.g.

// takes styles from h1
textMetrics.init(document.querySelector('h1'));

// takes styles from h1 and overwrites font-size
textMetrics.init(document.querySelector('h1'), {fontSize: '20px'});

// only use given styles
textMetrics.init({
  fontSize: '14px',
  lineHeight: '20px',
  fontFamily: 'Helvetica, Arial, sans-serif',
  fontWeight: 400,
  width: 100,
});

Methods

width([text, [options, [overwrites]]])
height([text, [options, [overwrites]]])
lines([text, [options, [overwrites]]])
maxFontSize([text, [options, [overwrites]]])

text

Type: string Defaults to el.innerText if an element is available

options

Type: object

key default description
multiline false The width of widest line instead of the width of the complete text

overwrites

Type: object

Use to overwrite styles

Performance

I've compared this module with a very naive jQuery implementation as well as the . See https://jsperf.com/bezoerb-text-metrics Even if Range.getBoundingClientRect should be considered as a performance bottleneck according to what-forces-layout by Paul Irish, i couldn't detect any sort of recalculate style and it massively outperforms textMetrics.height().

Compatibility

The normal build (3,2kb gzipped) should work well on modern browsers.
These builds are tested using
Browserstack

License

Copyright (c) 2016 Ben Zörb Licensed under the MIT license.

License

MIT © Ben Zörb

text-metrics's People

Contributors

bezoerb avatar dependabot[bot] avatar kuborgh-bzoerb avatar omerts avatar thor-x86 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

text-metrics's Issues

Calculate width of text filled with only (or mostly) whitespace

Is there a way to get text-metrics to include every whitespace when computing the width of a string?

With strings that are all whitespace or mostly whitespace, the width that text-metrics produces seems to be computed after stripping out whitespaces. At the least, the width results are smaller than when I just compute the width of the string using canvas.measureText. Here's an example of the mismatch:

https://codesandbox.io/s/text-metrics-whitespaces-mzgh2?file=/src/index.js

Am I just missing some CSS prop I need to pass to text-metrics to get it to understand how I want it to treat whitespaces?

I expected passing in pre or break-spaces to white-space would do this trick but it did not. Is it possible this "if block" should add whitespace to the line string before continue-ing if certain white-space values are present?

if (BAI.has(parts[i - 1]) && BAI.has(parts[i])) {

Also, I did see this issue but could not find the trim() culprit that was mentioned. The trim in normalizeWhitespace looks like it doesn't trim if white-space: pre is used, so I would think that should be fine.

export function normalizeWhitespace(text, ws) {

Computes lines with one very long word

I think it could be cool to split a word by length when it's too long. The idea will be to split a long word each part should have given maximum number of characters.

For example if we use lines method on a string like this Craspharetrapharetragravida.Vivamusconsequatlacusvelposuerecongue.Duisaloremvitaeexauctorscelerisquenoneuturpis.Utimperdietmagnasitametjustobibendumvehicula..

Actually it returns the same string, with the option wordwrap it should return something like the example just below.

[
        'Craspharetraphar-',
        'retragravida.Vivam-',
        'musconsequatlac-',
        'cusvelposuerecon-',
        'ngue.Duisaloremv-',
        'vitaeexauctorscel-',
        'lerisquenoneutur-',
        'rpis.Utimperdietma-',
        'agnasitametjustob-',
        'bibendumvehicul-',
        'la.'
]

Baseline measurement

Hello,
I'd like to know if you know/considered calculating the baseline height of a text.
My use case would be to align the baseline (of each line?) to other elements in a design tool.

This library is already useful for calculating height and width so thanks already!

Wrong conversion to pixels from points

Hey,

Thanks for the lib, really helpful.
Seems like there is a small bug with the conversion from pts to inch.
Current implementation:

return value / (96 / 72);

Should be:

return value * (96 / 72);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.