uni-app canvas文本自动换行

发布于:2024-10-11 ⋅ 阅读:(30) ⋅ 点赞:(0)

封装

支持单行文本超出换行。多行文本顺位排版

	// 填充自动换行的文本
	function fillFeedText({ctx, text, x, y, maxWidth, lineHeight, color, size}) {
		// 文本配置
		ctx.setFontSize(size);
		ctx.setFillStyle(color);

		// 计算文本换行宽高,换行逻辑
		const words = text.split('');
		let line = '';
		const lines = [];
		for (let i = 0; i < words.length; i++) {
			const word = words[i];
			const testLine = line + word;
			const metrics = ctx.measureText(testLine);
			if (metrics.width > maxWidth && i > 0) {
				lines.push(line);
				line = word;
			} else {
				line = testLine;
			}
		};

		// 填充文本
		lines.push(line);
		let nextStart = 0;
		lines.forEach((line, index) => {
			ctx.fillText(line, x, y + ((index++) * lineHeight), maxWidth);
			nextStart = y + ((index++) * lineHeight)
		});
	}

使用

// 文本集合
				const text = ["时间:" + Tool.now(), state.address, "第三行的文本 试试试试试试试试试试试试试试试试试试试试试试试试试试试试试试"]; // 需要填充两个文本
				let nextStart = state.height * 0.88;  // 文本的起点
				text.forEach((line) => {
					nextStart = fillFeedText({
						ctx,
						text: line,
						x: padding,
						y: nextStart,
						maxWidth: state.width - padding - 10,
						lineHeight,
						color: '#FFFFFF',
						size: 10
					})
				});

在这里插入图片描述

效果

在这里插入图片描述