zoukankan      html  css  js  c++  java
  • 小程序画布多行文本换行

    ctx.setFillStyle("#000");
        ctx.setTextAlign('left'); //是否居中显示,参考点画布中线
        ctx.font = 'normal bold 16px PingFang SC';
        var title ='阿斯顿发斯蒂芬克拉斯 剪短发拉 阿斯顿发送到发送 到发送时间段开了房间爱上';
        this.dealWords({
          ctx: ctx,//画布上下文
          fontSize: 14,//字体大小
          word: title,//需要处理的文字
          maxWidth: 295 * rpx,//一行文字最大宽度
          x: 20 * rpx,//文字在x轴要显示的位置
          y: 320* rpx,//文字在y轴要显示的位置
          maxLine: 2//文字最多显示的行数
        })
        ctx.draw();
    
      },
    
      // 多行文本
      dealWords: function (options) {
        options.ctx.setFontSize(options.fontSize);//设置字体大小
        var allRow = Math.ceil(options.ctx.measureText(options.word).width / options.maxWidth);//实际总共能分多少行
        var count = allRow >= options.maxLine ? options.maxLine : allRow;//实际能分多少行与设置的最大显示行数比,谁小就用谁做循环次数
        var endPos = 0;//当前字符串的截断点
        for (var j = 0; j < count; j++) {
          var nowStr = options.word.slice(endPos);//当前剩余的字符串
          var rowWid = 0;//每一行当前宽度 
          if (options.ctx.measureText(nowStr).width > options.maxWidth) {//如果当前的字符串宽度大于最大宽度,然后开始截取
            for (var m = 0; m < nowStr.length; m++) {
              rowWid += options.ctx.measureText(nowStr[m]).width;//当前字符串总宽度
              if (rowWid > options.maxWidth) {
                if (j === options.maxLine - 1) { //如果是最后一行
                  options.ctx.fillText(nowStr.slice(0, m - 1) + '...', options.x, options.y + (j + 1) * 14); //(j+1)*18这是每一行的高度 
                } else {
                  options.ctx.fillText(nowStr.slice(0, m), options.x, options.y + (j + 1) * 14);
                }
                endPos += m;//下次截断点
                break;
              }
            }
          } else {//如果当前的字符串宽度小于最大宽度就直接输出
            options.ctx.fillText(nowStr.slice(0), options.x, options.y + (j + 1) * 18);
          }
        }
      },
  • 相关阅读:
    登录Mysql看不到Mysql库
    七牛云使用记录
    FFmpeg工具
    解决VMware下CentOS连不上网络问题
    14.中介者模式
    二十三种设计模式(三)
    23种设计模式(二)
    搭建ssm环境
    文件的字符流与字节流读写
    设计模式之用工厂模式实现计算器
  • 原文地址:https://www.cnblogs.com/liweitao/p/14158462.html
Copyright © 2011-2022 走看看