Canvas Text Box is a JavaScript library that allows wrapping and measuring of the text on a canvas element. Text is wrapped inside the dimensions of the box. A background can be added to the text.
Reason behind the existence of this library is that native Canvas API does not have a method to wrap text onto the next line when a desired maximum width is reached.
let canvas1 = document.getElementById("example1-canvas");
canvasTextBox.draw(canvas1, text);
This will use default options when rendering the text. Multiple options are available to customize the appearance of text in the box
let options = {
option1: 'value1',
option2: 'value2',
...
};
canvasTextBox.draw(canvas1, text, options);
These options are used to generate string used for setting CanvasRenderingContext2D.font property. As stated, it is a DOMString parsed as CSS font value.
fontFamily: 'Tahoma, Geneva, sans-serif'font-family declarationfontStyle: 'normal',font-stylefontVariant: 'normal'font-variantfontWeight: 'normal'font-weightfontSize: 32, font-size in pixelslineHeight: 40, line-height in pixelstextFillStyle: '#000000'color of the text filltextAlign: 'left'alignment of the text within the text box. Accepted values:left,center
You can set a background for your text or for a whole textbox.
useBackground: falseset this totrueif you want your text(box) to have a background colorfullWidthBackground: falseset thistrueif you want that whole textbox has a background. Iffalse(default value) then only letters will have a background.backgroundFillStyle: 'rgba(50,50,50,0.5)'fill style of the background.
startX: 20X-axis start position in pixels (top left of the textbox)startY: 20Y-axis start position in pixels (top left of the textbox)width: 200width of the textbox in pixelsbottomAligned: falseset this totrueif you want your textbox to be bottom aligned relative to canvas. In that casestartYproperty is not relevant andmarginBottomwill be considered during calculationsmarginTop: 0not used in this versionmarginBottom: 20used whenbottomAlignedis set totrueto calculate the distance of the last line from the bottom of the canvasmarginLeft: 0not used in this versionmarginRight: 0not used in this versionpaddingLeft: 10used only to calculate spread of the background fill left of the textpaddingRight: 20used only to calculate spread of the background fill right of the text. Should be double ofpaddingLeftfor "nice looking results"paddingTop: 20used only to calculate spread of the background fill above the text
- Project official page: https://aleksandarjakovljevic.com/canvas-text-box/
Thanks goes to these wonderful people (emoji key):
Rasmuskrogh 💻 |
Aleksandar Jakovljevic 💻 |
This project follows the all-contributors specification. Contributions of any kind welcome!