canvas文字換行

上次項(xiàng)目中,涉及到文字換行的問題,如圖



可謂將換行做到了極致
解決方法:
將文字換行封裝為一個(gè)方法

        /**
         * 海報(bào)文字換行
         */
        fillTextWrap(ctx, text, x, y, maxWidth, lineHeight) {
            // 設(shè)定默認(rèn)最大寬度
            const systemInfo = wx.getSystemInfoSync()
            const deciveWidth = systemInfo.screenWidth
            // 默認(rèn)參數(shù)
            maxWidth = maxWidth || deciveWidth
            lineHeight = lineHeight || 20
            // 校驗(yàn)參數(shù)
            if (
            typeof text !== 'string' ||
            typeof x !== 'number' ||
            typeof y !== 'number'
            ) {
                return
            }
            // 字符串分割為數(shù)組
            const arrText = text.split('')
            // 當(dāng)前字符串及寬度
            let currentText = ''
            let currentWidth
            for (let letter of arrText) {
                currentText += letter
                currentWidth = ctx.measureText(currentText).width
                if (currentWidth > maxWidth) {
                    ctx.fillText(currentText, x, y)
                    currentText = ''
                    y += lineHeight
                }
            }
            if (currentText) {
                ctx.fillText(currentText, x, y)
            }
        }

調(diào)用方法繪制文字

ctx.setFillStyle('red')
ctx.setFontSize(26)
// ctx.setTextAlign('center')
//使文字換行顯示
const textHeightL = that.fillTextWrap(
    ctx,
    that.renderData.springScrolls.L,
    50,
    313-(that.renderData.springScrolls.L).length*26/2, //為了讓文字垂直居中
    18,
    36
)
const textHeightR = that.fillTextWrap(
      ctx,
      that.renderData.springScrolls.R,
      275,
      313-(that.renderData.springScrolls.R).length*26/2,//為了讓文字垂直居中
      18,
      36
      )

OK,問題得到解決希望能幫到你們

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • canvas元素的基礎(chǔ)知識(shí) 在頁面上放置一個(gè)canvas元素,就相當(dāng)于在頁面上放置了一塊畫布,可以在其中進(jìn)行圖形的...
    oWSQo閱讀 10,440評論 0 19
  • 1 CALayer IOS SDK詳解之CALayer(一) http://doc.okbase.net/Hell...
    Kevin_Junbaozi閱讀 5,336評論 3 23
  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對...
    cosWriter閱讀 11,656評論 1 32
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,316評論 4 61
  • D22 ~ LESSON 22 今天,我明白我所有的體驗(yàn)都是有原因的,我選擇看待每個(gè)經(jīng)驗(yàn)都是我療愈任務(wù)的一部分。因...
    梅曉云閱讀 717評論 0 0

友情鏈接更多精彩內(nèi)容