最近做一個刮刮卡,需要將文字在canvas中水平、垂直居中

wxml
<canvas type='2d' id="myCanvas" width="300" height="150" style="background:yellow;" \&;
使用canvas2d構建畫布

藍色線為水平中線
紅色線為垂直中線
文本設置方法
fillText
方法為canvas設置文本方法,使用如下所示
ctx.fillText('文本內(nèi)容', x, y)
x為橫軸坐標
y為縱軸坐標
上例將文本內(nèi)容設置在canvas畫布的坐標位置上,跳脫web的開發(fā)思維,我們可以認為X點相對于文本有左,中,右三種布局,Y點相對于文本有上、中、下的布局,這樣就很好理解文本在canvas上是如何繪制了
水平居中
找到X軸的中點位置,如上圖,在150px這個點上
注意X點相對于文本的位置
ctx.fillStyle = '#aaa'
ctx.font = 'bold 30px "Gill Sans Extrabold"'
ctx.textAlign = 'center'
ctx.fillText('文本內(nèi)容', 150, 0)

圖示只作說明
垂直居中
找到X軸的中點位置,如上圖,在75px這個點上
注意Y點相對于文本的位置
ctx.fillStyle = '#aaa'
ctx.font = 'bold 30px "Gill Sans Extrabold"'
ctx.textBaseline = 'middle'
ctx.fillText('文本內(nèi)容', 0, 75)

圖示只作說明
完美居中
ctx.fillStyle = '#aaa'
ctx.font = 'bold 30px "Gill Sans Extrabold"'
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
ctx.fillText(opts.maskerTitle, left, top)
總結
以上所述是小編給大家介紹的小程序中canvas實現(xiàn)水平、垂直居中效果,希望對大家有所幫助!