- Multiline text
- Auto line breaks
- Horizontal Align
- Vertical Align
- Easy Debugging
See Demo: Here
npm install canvas-txt --save
or
yarn add canvas-txt
<canvas id="myCanvas" width="500" height="500"></canvas>
import canvasTxt from 'canvas-txt'
var c = document.getElementById('myCanvas')
var ctx = c.getContext('2d')
var txt = 'Lorem ipsum dolor sit amet'
canvasTxt.fontSize = 24
canvasTxt.drawText(ctx, txt, 100, 200, 200, 200)
//canvasTxt.drawText(ctx,txt,x,y,width,height);
See fiddle : here
<script src="//unpkg.com/canvas-txt"></script>
var canvasTxt = window.canvasTxt.default
/// ...remaining same as webpack
Properties | Default | Description |
---|---|---|
debug |
false |
Shows the border and align gravity for debugging purposes |
align |
center |
Text align. Other possible values: left , right |
vAlign |
middle |
Text vertical align. Other possible values: top , bottom |
fontSize |
14 |
Font size of the text in px |
font |
Arial |
Font family of the text |
fontStyle |
'' |
Font style, same as css font-style. Examples: italic , oblique 40deg |
fontVariant |
'' |
Font variant, same as css font-variant. Examples: small-caps , slashed-zero |
fontWeight |
'' |
Font weight, same as css font-weight. Examples: bold , 100 |
lineHeight |
null |
Line height of the text, if set to null it tries to auto-detect the value |
Method | Description |
---|---|
drawText(ctx,text,x,y,width,height) |
To draw the text to the canvas |
import canvasTxt from 'canvas-txt'
var c = document.getElementById('myCanvas')
var ctx = c.getContext('2d')
//You can use \n to define custom line breaks
var txt = 'Lorem \nipsum dolor sit amet'
//You can also use other methods alongside this
ctx.fillStyle = '#ff0000' //red color text
canvasTxt.font = 'Verdana'
canvasTxt.fontSize = 20
canvasTxt.align = 'left'
canvasTxt.lineHeight = 60
canvasTxt.debug = true //shows debug info
canvasTxt.drawText(ctx, txt, 100, 200, 200, 200)
A wrapper of this library is available for react. Check neomusic/react-canvas-txt