小程序 canvas 控制文字的换行以及定位函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | /* * ctx: 画布上下文 * word: 需要处理的文字 * maxWidth:一行文字最大宽度 * x: 文字在x轴要显示的位置 * y: 文字在y轴要显示的位置 * maxLine: 文字最多显示的行数 */ <br> //传入一个对象包含以上的值 dealWords(options) { options.ctx.font = "12px Arial" ; //设置字体大小 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); } } }, |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步