收藏
回答

canvas绘图文字换行,第一行文字少计算一个字宽度

框架类型 问题类型 API/组件名称 终端类型 微信版本 基础库版本
小程序 Bug canvas 客户端 7.0.3 2.5.1
/**
   * 绘制多行文本
   * @param ctx canvas对象
   * @param str 文本
   * @param leftWidth 距离左侧的距离
   * @param initHeight 距离顶部的距离
   * @param titleHeight 文本行高
   * @param canvasWidth 文本区宽度
   * @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 个回答

  • 邱一欢
    邱一欢
    2019-02-22

    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;

        }


    2019-02-22
    有用 1
    回复
  • 努力努力要努力zzz
    努力努力要努力zzz
    2019-02-21

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

    2019-02-21
    有用 1
    回复
登录 后发表内容