canvas 文字超出显示省略号

项目实例,点击可查看

以uni-app框架为例:可以把画图封装成一个函数调用。

	activityCanvas: function(arrImages, storeName, price, people, count, successFn) {
		let that = this;
		let rain = 2;
		const context = uni.createCanvasContext('activityCanvas');
		context.clearRect(0, 0, 0, 0);
		/**
		 * 只能获取合法域名下的图片信息,本地调试无法获取
		 * 
		 */
		context.fillStyle = '#fff';
		context.fillRect(0, 0, 594, 850);
		uni.getImageInfo({
			src: arrImages[0],
			success: function(res) {
				context.drawImage(arrImages[0], 0, 0, 594, 850);
				context.setFontSize(14*rain);
				context.setFillStyle('#333333');
				// 绘制文字自动换行
				that.canvasWraptitleText(context, storeName, 112*rain, 110*rain, 250*rain, 30*rain, 1*rain)
			   ... // 这里可绘制自己项目的内容
				context.draw(true, function() {
					uni.canvasToTempFilePath({
						canvasId: 'activityCanvas',
						fileType: 'png',
						destWidth: 594,
						destHeight: 850,
						success: function(res) {
							// uni.hideLoading();
							successFn && successFn(res.tempFilePath);
						}
					})
				});

			},
			fail: function(err) {
				console.log('失败', err)
				uni.hideLoading();
				that.Tips({
					title: '无法获取图片信息'
				});
			}
		})
	},

文字超出显示省略号单独封装一个函数调用。

/**
	 * 绘制文字自动换行
	 * @param array arr2 海报素材
	 * @param Number x , y 绘制的坐标
	 * @param Number maxWigth 绘制文字的宽度
	 * @param Number lineHeight 行高
	 * @param Number maxRowNum 最大行数
	 */
	canvasWraptitleText(canvas, text, x, y, maxWidth, lineHeight, maxRowNum) {
		if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number') {
			return;
		}
		// canvas.font = '20px Bold PingFang SC'; //绘制文字的字号和大小
		// 字符分隔为数组
		var arrText = text.split('');
		var line = '';
		var rowNum = 1
		for (var n = 0; n < arrText.length; n++) {
			var testLine = line + arrText[n];
			var metrics = canvas.measureText(testLine);
			var testWidth = metrics.width;
			if (testWidth > maxWidth && n > 0) {
				if (rowNum >= maxRowNum) {
					var arrLine = testLine.split('')
					arrLine.splice(-9)
					var newTestLine = arrLine.join("")
					newTestLine += "..."
					canvas.fillText(newTestLine, x, y);
					//如果需要在省略号后面添加其他的东西,就在这个位置写(列如添加扫码查看详情字样)
					//canvas.fillStyle = '#2259CA';
					//canvas.fillText('扫码查看详情',x + maxWidth-90, y);
					return
				}
				canvas.fillText(line, x, y);
				line = arrText[n];
				y += lineHeight;
				rowNum += 1
			} else {
				line = testLine;
			}
		}
		canvas.fillText(line, x, y);
	}

具体代码示例可查看开源项目

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值