node-canvas-text
Draws your string on a canvas, fit inside of a rectangle. I had to make this, because measureText() from node-canvas is unpredictable, and ignores font selectors besides font-size and font-family.
Requirements:
- node-canvas to draw onto
- opentype.js to load OpenType fonts
Installation
npm install node-canvas-text canvas opentype.js --save
Parameters
This module exports a single function with signature:
- context from node-canvas
- a string to draw
- font object
- bounding rectangle
{ x, y, width, height }
- options
{ minSize, maxSize, granularity, hAlign, vAlign, fitMethod, drawRect }
Options
- minSize: minimum font size
float
- maxSize: maximum font size
float
- granularity: a step, in which to scale font size
float
- hAlign: horizontal text alignment
'left' | 'center' | 'right'
- vAlign: vertical text alignment
'top' | 'center' | 'bottom'
- fitMethod:
'baseline' | 'box'
- drawRect: draw the bounding rectangle
'true' | 'false'
- textFillStyle: fill style for text
string
- rectFillStyle: fill style for rectangle
string
- rectFillOnlyText: fill only the exact resulting text rectangle, not the bounding one
'true' | 'false'
- textPadding: text padding
float
- fillPadding: fill padding
float
Defaults
minSize: 10 maxSize: 200 granularity: 1 hAlign: 'left' vAlign: 'bottom' fitMethod: 'box' textFillStyle: '#000' rectFillStyle: '#fff' rectFillOnlyText: false textPadding: 0 fillPadding: 0 drawRect: false
Fit method: box vs baseline
Example
let canvas = imgWidth imgHeight;let ctx = canvas; // Load OpenType fonts from fileslet titleFont = opentype;let priceFont = opentype;let barcodeFont = opentype; // Strings to drawlet titleString = "A string, but not too long" priceString = "200" barcodeString = "54490000052117"; // Calculate bounding rectangleslet headerRect = x: 0 y: 0 width: canvaswidth height: canvasheight / 35 ; let priceRect = x: canvaswidth / 2 y: headerRectheight width: canvaswidth / 2 height: canvasheight - headerRectheight ; let barcodeRect = x: 0 y: headerRectheight + priceRectheight / 2 width: canvaswidth - priceRectwidth height: priceRectheight / 2; // Drawlet drawRect = true; ; ; ;