wxml:
<canvas style="position: absolute; top: 0; left: 0;right:0;width:100%;" canvas-id="firstCanvas"></canvas>
javascript:
onReady: function () {
var that = this
setTimeout(() => {
this.drawCanvas(that)
},500)
}
drawCanvas: function (that) {
var context = wx.createCanvasContext('firstCanvas')
context.setFillStyle('#F2F6FC')
context.fillRect(0, 0, 750, 600)
context.setFillStyle('#303133')
context.setTextBaseline('middle')
context.setFontSize(24)
that.drawText(context, '錫盟信息萬事通', 20, 30, 330, 330)
context.setFontSize(18)
that.drawText(context, that.data.content, 20, 70, 330, 330)
context.draw()
}
//文本換行 參數:1、canvas對象,2、文本 3、距離左側的距離 4、距離頂部的距離 5、6、文本的寬度
drawText: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
var lineWidth = 0;
var lastSubStrIndex = 0; //每次開始截取的字符串的索引
for (let i = 0; i < str.length; i++) {
lineWidth += ctx.measureText(str[i]).width;
if (lineWidth > canvasWidth) {
ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //繪製截取部分
initHeight += 22; //22爲字體的高度
lineWidth = 0;
lastSubStrIndex = i;
titleHeight += 30;
}
if (i == str.length - 1) { //繪製剩餘部分
ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
}
}
// 標題border-bottom 線距頂部距離
titleHeight = titleHeight + 10;
return titleHeight
}
微信小程序畫布實現文本換行
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.