Syntax
CanvasTextWrapper(HTMLCanvasElement, String [, Options]);
Options
- is an object with the following available properties and values:
-
font(String) - text style that includes font size in px, weight, font family, etc. Similar to CSS font shorthand property
-
lineHeight(Number or String)
- number - n times font size where 1 is equivalent to '100%'
- "%"
- "px"
-
textAlign(String) - horizontal alignment of each line
- "left"
- "center"
- "right"
-
verticalAlign(String) - vertical alignment of the whole text block
- "top"
- "middle"
- "bottom"
-
paddingX(Number) - horizontal padding (in px) set equally on both, left and right sides
-
paddingY(Number) - vertical padding (in px) set equally on both, top and bottom sides
-
fitParent(Boolean) - parameter that controls which element to fit
- true - fit canvas parent's width instead of canvas own width
- false - fit canvas width
-
lineBreak(String) - text split rule
- "auto" - text fills padded container going to a next line on a whole word
- "word" - each next word will be placed on a new line
-
sizeToFill(Boolean) - auto font size to fill text container
- true - ignore given font size/line height and resize text to fill its padded container
- false - use specified or default font size
-
strokeText(Boolean) - if enabled, all lines match the same width with flexed spaces between words (one-word lines are ignored)
-
justifyLines(Boolean) - if enabled, text breaks on every new line character "\n"
NOTE: if a single word is too long to fit the width with specified font size, it will break on any letter unless "sizeToFill" option is enabled.
Default Options
{
font: "18px Arial, sans-serif",
lineHeight: 1,
textAlign: "left",
verticalAlign: "top",
paddingX: 0,
paddingY: 0,
fitParent: false,
lineBreak: "auto",
sizeToFill: false,
allowNewLine: true,
justifyLines: false,
strokeText: false
}
Usage
Configure context settings properties such as "fillStyle", "lineWidth" or "strokeStyle" before using CanvasTextWrapper like so:
var canvas = document.getElementById("#canvasText");
canvas.width = 200;
canvas.height = 200;
context = canvas.getContext("2d");
context.lineWidth = 2;
context.strokeStyle = "#ff0000";
CanvasTextWrapper(canvas,"Hello"); //default options will apply
Installation
bower install canvas-text-wrapper
npm install canvas-text-wrapper