1.1.2 • Published 2 years ago

canvas-fit-text v1.1.2

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

Canvas Fit Text

Update After some more testing, the intended functionality does not work at larger font sizes; I don't remember specifics. Give it a whirl if you want, but seems to only work well at small font sizes.

Fit-text for canvas, with optional line-wrapping.
Integrates with and preserves the context's current font value.

Installation

Install w/ yarn or npm...

yarn add canvas-fit-text

...and import into your projct.

# ES6
import fitText from 'canvas-fit-text';

# or CommonJS
var fitText = require('canvas-fit-text');

Or download the repo and copy dist/canvas-fit-text.js to your project.

Usage

CanvasFitText extends the native CanvasRenderingContext2D.
Use it directly on the context.

let canvas = document.querySelect('canvas'),
  ctx = canvas.getContext('2d');

// Fit to width 200px.
ctx.fitText('Hello world!', 0, 0, 200);

// Fit to width 200px.
// Constrain to height 100px (which also enables line wrapping)
let text = 'Hello world! How are you? Ok byeee!';
ctx.fitText(text, 0, 0, 200, 100);

Original context font value is preserved (after fit).

let canvas = document.querySelect('canvas'),
  ctx = canvas.getContext('2d');

// Current font
ctx.font = '12px sans-serif';

// Will print at ~439px sans-serif
ctx.fitText('foo', 0, 0, 600);

// Font was reverted back.
console.log(ctx.font);
// ➜ 12px sans-serif

Usage args

ArgRequiredDescriptionType
textYesThe text to printString
xYesX coordinate to start printingString
yYesY coordinate to start printingString
widthYesMax width text can expand toNumber
heightNoEnables line wrapping. Sets max height text can expand to.Number

Notes

Setting height will constrain max-height. Not min-height. So, setting width and height will often leave vertical and horizontal space.

With only the width prop, the text will fit horizontally right to the edge.

1.1.2

2 years ago

1.1.1

3 years ago

1.1.0

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago