1.0.3 • Published 3 years ago

get-text-width v1.0.3

Weekly downloads
6
License
ISC
Repository
github
Last release
3 years ago

getTextWidth

This helper function is intended to get the rendered width of text. It leverages canvas to simulate the rendered text and calculate the width using the font of your project.

It also has a backup height:width ratio number in case something goes wrong with the canvas.

Returns numeric value of width in pixels

Example

Here is an example of how to implement this function.

import { getTextWidth } from 'get-text-width';

const width = getTextWidth("Hello world");

// The function also accepts as custom 
// backup font height:width ratio like so:
const width = getTextWidth("Hello world", 0.5);

Live demo

Common fonts height:width aspect ratios

FontAspect ratio
Arial0.52
Arial Black0.52
Calibri0.46
Candara0.47
Century Gothic0.53
Corbel0.46
DejaVu Sans0.55
DejaVu Sans Condensed0.55
DejaVu Sans Light0.55
Eurostile0.47
Franklin Gothic0.49
Futura0.51
Gadget0.55
Geneva0.55
Gill Sans0.45
GNU Free Sans0.53
Goudy Sans0.48
Helvetica0.52
Helvetica Neue0.52
Impact0.65
Liberation Sans0.53
Lucida Grande0.53
Lucida Sans Unicode0.53
Myriad0.48
Optima0.47
Serpentine BoldBold0.47
Stone Sans0.52
Tahoma0.55
Trebuchet MS0.52
Verdana0.55
FontAspect ratio
Baskerville0.45
Bernhard Modern0.34
Big Caslon0.47
Book Antiqua0.46
Bookman Old Style0.47
Calisto MT0.47
Cambria0.47
Century0.46
Century Schoolbook0.46
Cochin0.37
Constantia0.45
DejaVu Serif0.52
DejaVu Serif Condensed0.52
Didot0.43
Garamond0.38
Georgia0.48
GNU Free Serif0.45
Goudy Old Style0.40
Hoefler Text0.44
Humana Serif0.50
Janson Text0.43
Liberation Serif0.46
Minion0.45
New York0.55
Palatino0.46
Times New Roman0.45
FontAspect ratio
Andale Mono0.51
Consolas0.49
Courier New0.43
DejaVu Mono0.55
GNU Free Mono0.42
Liberation Mono0.53
Lucida Console0.53
FontAspect ratio
URW Alcuin SCT0.51
American Typewriter0.51
Barbedor0.49
Caflisch Script0.37
Chalkboard0.53
Charlemagne0.74
Comic Sans MS0.55
Copperplate0.44
Corsiva0.60
Flemish Script0.28
Herculanum0.61
Marker Felt0.62
Papyrus0.46
Sand0.69
Textile0.68

       

Happy coding! 🗒