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), font 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 for the whole text block
- "top"
- "middle"
- "bottom"
-
paddingX(Number) - horizontal padding (in px) that is equally set on left and right
-
paddingY(Number) - vertical padding (in px) that is equally set on top and bottom
-
fitParent(Boolean) - fit canvas container's size instead of its own size
-
lineBreak(String) - text split rule
- "auto" - text goes to the next line on a whole word when there's no more room
- "word" - each next word is placed on a new line
-
sizeToFill(Boolean) - ignore given font size and line height and resize text to fill its padded container
-
strokeText(Boolean) - allow text outline based on canvas context configuration
-
justifyLines(Boolean) - all lines match the same width with flexed spaces between words
-
allowNewLine(Boolean) - text breaks on new line character '\n'. Supports multiple consecutive new lines.
-
renderHDPI(Boolean) - text is rendered based on device pixel ratio
-
textDecoration(String) - additional text decoration
- "none"
- "underline" - text is underlined according to "context.strokeStyle" and "context.lineWidth"
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, renderHDPI: true, textDecoration: "none" }
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, {strokeText: true});
Installation
npm install canvas-text-wrapper --save
bower install canvas-text-wrapper