canvas绘图文字换行,第一行文字少计算一个字宽度
发布于 5 年前 作者 qmo 12964 次浏览 来自 问答
/**
   * 绘制多行文本
   * [@param](/user/param) ctx canvas对象
   * [@param](/user/param) str 文本
   * [@param](/user/param) leftWidth 距离左侧的距离
   * [@param](/user/param) initHeight 距离顶部的距离
   * [@param](/user/param) titleHeight 文本行高
   * [@param](/user/param) canvasWidth 文本区宽度
   * [@returns](/user/returns) {*}
   */
  drawText: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
    let lineWidth = 0;
    let 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 += titleHeight;
        lineWidth = 0;
        lastSubStrIndex = i;
      }
      if (i == str.length - 1) { //绘制剩余部分
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
      }
    }
  },
 onLoad: function (options) {
    const ctx = wx.createCanvasContext('scene');
    const canvasWidth = 300;
    const canvasHeight = 400;
    const bgColor= '#577C8A';
    //开始绘制背景区
    ctx.setFillStyle(bgColor)
    ctx.fillRect(0, 0, canvasWidth, canvasHeight)
    //开始绘制文字区
    ctx.setFontSize(18);
    ctx.setFillStyle('#fff');
    let str = '哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈';
    this.drawText(ctx, str, 50, 200, 22, 200);// 调用行文本换行函数
 
 
    ctx.draw()
},

用canvas做文本换行的时候 第一行的长度总是少了一个字的宽度呢?

2 回复

this.CalculateText=function(text,width)

    {

        var aryText=[];

        var outText=’’;

        var word=null,preWord=null;

        for(var i=0;i<text.length;++i)

        {

            word=text[i];

            if (word==’\r’) //换行

            {

                aryText.push(outText);

                outText = ‘’;

            }

            else if (word==’\n’)

            {

                if (preWord!=’\r’//\r\n 不处理

                {

                    aryText.push(outText);

                    outText = ‘’;

                }

            }

            else

            {

                outText+=text[i];

                var textWidth = this.Canvas.measureText(outText).width;

                if (textWidth>=width)

                {

                    aryText.push(outText);

                    outText=’’;

                }

            }

            preWord = word;

        }

        if (outText.length > 0) aryText.push(outText);

        console.log(aryText)

        return aryText;

    }

substring 方法返回的子串包括 start 处的字符,但不包括 stop 处的字符。

回到顶部