18.微信小程序之canvas绘制多行文本自动换行,支持换行符换行

canvas中的文本由用户输入,因此需要把一堆文字进行换行。当用户按下回车键进行换行时,也得将换行信息绘制出来。

drawText:function(ctx,item,initHeight,titleHeight){
    console.log('传入的initHeight is '+initHeight);
    console.log('传入的titleHeight is ' + titleHeight);
    var lineWidth = 0;
    //每次开始截取的字符串的索引
    var lastSubStrIndex = 0;
    for (var i = 0; i < item.length; i++) {
      lineWidth += ctx.measureText(item[i]).width;
      if (lineWidth > 315) {
        //绘制截取部分
        ctx.fillText(item.substring(lastSubStrIndex, i), 30, initHeight);
        //14为字体的高度
        initHeight += 20;
        lineWidth = 0;
        lastSubStrIndex = i;
        titleHeight += 20;
      }
       //绘制剩余部分
      if (i == item.length - 1) {
        ctx.fillText(item.substring(lastSubStrIndex, i + 1), 30, initHeight);
      }
    }
    console.log('结束一轮之后的initheight: '+initHeight+' titleHeight: '+titleHeight);
    return initHeight+','+titleHeight;
  },

drawImage() {
    var that = this;
    var headCoach = '/image/headCoach.png';
    var onePrize = '/image/twoPrize.png';
    var twoPrize = '/image/twoPrize.png';
    var code = '/image/code.jpg';
    var str = '啦啦啦啦啦啦啦啦啦啦啦啦:啦啦啦\r\n当一个组件上的事件被触发后,该事件会向父节点传递冒泡事件.\r\n哈哈哈哈哈哈哈哈哈哈或或或或或哈哈哈哈哈哈或或或或或\r\n今天吃是没什么没什么没什么什么什么没什么事吗什么秘书吗\r\n啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦~';
    var lineWidth = 0;
    var lastSubStrIndex = 0;
    //文本绘制的初始高度
    //因为我绘制的是长图,所以初始高度很高。。
    var initHeight = 870;
    //绘制文本的高度
    var titleHeight = 900;
    const ctx = wx.createCanvasContext('myCanvas');
    ctx.setFillStyle('#D6554C');
    ctx.fillRect(0, 0, 375, 2400);
    ctx.drawImage(headCoach, 165, 20, 45, 45);
    ctx.setFillStyle('#FFFFFF');
    ctx.setFontSize(12);
    ctx.setTextAlign('center');
    ctx.fillText('某某某', 187, 85);
    ctx.setTextAlign('left');
    ctx.setLineWidth(1);
    ctx.setFontSize(14);
    ctx.setFillStyle('gray');
    
    var textArray = str.split('\r\n');
    console.log(textArray);
    for (var j = 0; j < textArray.length; j++) {
      var item = textArray[j];
      var isHeight=that.drawText(ctx,item,initHeight,titleHeight);
      var divideHeight = isHeight.split(',');
      initHeight = Number(divideHeight[0])+20;
      titleHeight = Number(divideHeight[1])+20;
    }
    
    console.log('绘制完成titleHeight is '+titleHeight);
    ctx.setFillStyle('#D6554C');
    ctx.fillRect(0, titleHeight - 35, 375, 15);
    that.setData({
      titleHeight: titleHeight-20
    });
    ctx.draw(false, function () {
      that.saveCanvasImage();
    });
  },

 

你可能感兴趣的:(微信小程序)