canvans画图时,文字分行

dealWords: function (options) {
        options.ctx.setFontSize(options.fontSize);//设置字体大小
        options.ctx.setFillStyle(options.fillstyle);//设置字体大小
        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) * 18);    //(j+1)*18这是每一行的高度        
                        } else {
                            options.ctx.fillText(nowStr.slice(0, m), options.x, options.y + (j + 1) * 18);
                        }
                        endPos += m;//下次截断点
                        break;
                    }
                }
            } else {//如果当前的字符串宽度小于最大宽度就直接输出
                options.ctx.fillText(nowStr.slice(0), options.x, options.y + (j + 1) * 18);
            }
        }
    },

调用:

 this.dealWords({
         ctx: ctx,//画布上下文
         fontSize: 18,//字体大小
         fillstyle:'#333333',
         word: text,//需要处理的文字
         maxWidth: 325,//一行文字最大宽度
         x: 10,//文字在x轴要显示的位置
         y: 285,//文字在y轴要显示的位置
         maxLine: 2//文字最多显示的行数
     });

 

posted @ 2019-08-15 09:18  爱学习的土豆  阅读(452)  评论(0编辑  收藏  举报