uniapp canvas draws text (supports automatic text wrapping, carriage return or line break, and punctuation does not start)

/**
 * 文字自动换行
 * @param {Object} ctx         画布的上下文环境
 * @param {Object} content     需要绘制的文本内容
 * @param {Object} drawX       绘制文本的x坐标
 * @param {Object} drawY       绘制文本的y坐标
 * @param {Object} lineHeight  文本之间的行高
 * @param {Object} lineMaxWidth 每行文本的最大宽度
 * @param {Object} lineNum     最多绘制的行数
 */
export default function useTextPrewrap(ctx, content, drawX, drawY, lineHeight, lineMaxWidth, lineNum, isTitle = false) {
    
    
	var drawTxt = ''; // 当前绘制的内容
	var drawLine = 1; // 第几行开始绘制
	var drawIndex = 0; // 当前绘制内容的索引
	//匹配这些中文标  。   ?      !     ,     、     ;      :     ”      '       )     》     〉      】     』     」      〕    …      ¥
	let reg = /[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201d|\u2019|\uff09|\u300b|\u3009|\u3011|\u300f|\u300d|\u3015|\u2026|\uffe5]/;
	// 判断内容是否可以一行绘制完毕
	if(ctx.measureText(content).width <= lineMaxWidth ) {
    
    
		ctx.fillText(content.substring(drawIndex, i), drawX, drawY);
	} else {
    
    
		for (var i = 0; i < content.length; i++) {
    
    
			drawTxt += content[i];
			if(content[i] === '\n') {
    
    
				ctx.fillText(content.substring(drawIndex, i + 1), drawX, drawY);
				drawIndex = i + 1;
				drawLine += 1;
				drawY += lineHeight;
				drawTxt = '';
				if(drawLine >= lineNum) {
    
    
					break;
				} else {
    
    
					continue;
				}
			};
			if (ctx.measureText(drawTxt).width >= lineMaxWidth && !reg.test(content[i + 1]) && i !== content.length - 1) {
    
    
				if (drawLine >= lineNum) {
    
    
					ctx.fillText(content.substring(drawIndex, i) + '..', drawX, drawY);
					break;
				} else {
    
    
					ctx.fillText(content.substring(drawIndex, i + 1), drawX, drawY);
					drawIndex = i + 1;
					if(content[i + 1] !== '\n') {
    
    
						drawLine += 1;
						drawY += lineHeight;
					}
					drawTxt = '';
				}
				// drawLine -= 1;
			} else {
    
    
				// 内容绘制完毕,但是剩下的内容宽度不到lineMaxWidth
				if (i === content.length - 1) {
    
    
					ctx.fillText(content.substring(drawIndex), drawX, drawY);
				}
			}
		}
	}
	return {
    
    
		x: drawX,
		y: drawY
	};
}

1. What is returned yis the position of the axis that has been drawn y, and this variable can be used to calculate the starting position of the drawing of the following content.
2. If the punctuation included in the regular pattern is drawn at the beginning of a line, the punctuation will be brought to the end of the previous line, so as to achieve the effect that the punctuation does not start.
3. Support carriage return and line feed

Guess you like

Origin blog.csdn.net/honeymoon_/article/details/125488267