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: false
set this totrue
if you want your text(box) to have a background colorfullWidthBackground: false
set thistrue
if 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: 20
X-axis start position in pixels (top left of the textbox)startY: 20
Y-axis start position in pixels (top left of the textbox)width: 200
width of the textbox in pixelsbottomAligned: false
set this totrue
if you want your textbox to be bottom aligned relative to canvas. In that casestartY
property is not relevant andmarginBottom
will be considered during calculationsmarginTop: 0
not used in this versionmarginBottom: 20
used whenbottomAligned
is set totrue
to calculate the distance of the last line from the bottom of the canvasmarginLeft: 0
not used in this versionmarginRight: 0
not used in this versionpaddingLeft: 10
used only to calculate spread of the background fill left of the textpaddingRight: 20
used only to calculate spread of the background fill right of the text. Should be double ofpaddingLeft
for "nice looking results"paddingTop: 20
used 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!