uni-app canvas文本自动换行

封装

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

javascript 复制代码
	// 填充自动换行的文本
	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)
		});
	}

使用

javascript 复制代码
// 文本集合
				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
					})
				});

效果

相关推荐
予你@。2 天前
UniApp + Vue3 实现 Tab 点击滚动定位(微信小程序)
微信小程序·小程序·uni-app
游戏开发爱好者82 天前
完整教程:App上架苹果App Store全流程指南
android·ios·小程序·https·uni-app·iphone·webview
予你@。2 天前
uni-app progress 组件使用详解
uni-app
iOS阿玮2 天前
春节提审高峰来袭!App Store 审核时长显著延长。
uni-app·app·apple
2501_916007472 天前
ios上架 App 流程,证书生成、从描述文件创建、打包、安装验证到上传
android·ios·小程序·https·uni-app·iphone·webview
2501_915106323 天前
iPhone 文件管理,如何进行应用沙盒文件查看
android·ios·小程序·https·uni-app·iphone·webview
2501_915921433 天前
Fastlane 结合 AppUploader 来实现 CI 集成自动化上架
android·运维·ci/cd·小程序·uni-app·自动化·iphone
云游云记3 天前
vue2 vue3 uniapp (微信小程序) v-model双向绑定
微信小程序·uni-app·vue
2501_915921433 天前
iOS 抓包怎么绕过 SSL Pinning 证书限制,抓取app上的包
android·网络协议·ios·小程序·uni-app·iphone·ssl
予你@。4 天前
uni-app(Vue3)实现自定义 Tab 切换滑块效果(微信小程序)
vue.js·微信小程序·uni-app