canvas画 圆角矩形 多行文本

224 阅读1分钟

		/**
		 * 画圆角矩形
		 * @param {*} ctx
		 * @param {*} x  圆角矩形起始坐标x
		 * @param {*} y  圆角矩形起始坐标y
		 * @param {*} width 矩形宽度
		 * @param {*} height 矩形高度
		 * @param {*} r 矩形圆角
		 * @param {*} color 矩形填充颜色
		 */
		drawRoundedRectangle(ctx, x, y, width, height, r, color) {
			ctx.moveTo(x + r, y);
			ctx.lineTo(x + width - r, y);
			ctx.arc(x + width - r, y + r, r, Math.PI * 1.5, Math.PI * 2);
			ctx.lineTo(x + width, y + height - r);
			ctx.arc(x + width - r, y + height - r, r, 0, Math.PI * 0.5);
			ctx.lineTo(x + r, y + height);
			ctx.arc(x + r, y + height - r, r, Math.PI * 0.5, Math.PI);
			ctx.lineTo(x, y + r);
			ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);

			ctx.fillStyle = color; //矩形填充颜色
			ctx.fill();
		},
checkLineMaxWidth(ctx, content, drawX, drawY, lineHeight, lineMaxWidth, lineNum) {
			let drawTxt = ''; // 当前绘制的内容
			let drawIndex = 0; // 当前绘制内容的索引
			let drawLine = 1; // 第几行开始绘制
			//lineNum 行数

			// 判断内容是否可以一行绘制完毕
			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 (ctx.measureText(drawTxt).width >= lineMaxWidth) {
						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;
							drawLine += 1;
							drawY += lineHeight;
							drawTxt = '';
						}
					} else {
						// 内容绘制完毕,但是剩下的内容宽度不到lineMaxWidth
						if (i === content.length - 1) {
							ctx.fillText(content.substring(drawIndex), drawX, drawY);
						}
					}
				}
			}
		},