1.文字横排两行
wrapText(ctx, text4, 24,334, 180,32);
function wrapText(ctx, text, startX, startY, maxWidth, wordsHight) {
let lineWidth = 0;
let lastSubStrIndex = 0;
// text = text.split('').join(' ')
let nameWidth = ctx.measureText(text).width
let line = 1
if (!text) return
for (let i = 0; i < text.length; i++) {
lineWidth += ctx.measureText(text[i]).width+1
if(line > 2) { // 渲染两行
break;
}
if (lineWidth > maxWidth) {
let tempText = '';
if (line === 2) {
tempText = text.substring(lastSubStrIndex, i - 2) + '...'
} else if (line < 2) {
tempText = text.substring(lastSubStrIndex, i)
}
ctx.strokeText(tempText, startX, startY)
ctx.fillText(tempText, startX, startY)
startY += wordsHight
lineWidth = 0;
lastSubStrIndex = i
line++
}
if (i == text.length -1 && line <= 2) {
ctx.strokeText(text.substring(lastSubStrIndex, i + 1), startX, startY)
ctx.fillText(text.substring(lastSubStrIndex, i + 1), startX, startY)
}
}
}
2.创建圆角矩形与文字
参考地址 :https://www.cnblogs.com/dyy-dida/p/14651882.html
// 设置圆角的半径
const radius = 15;
// 测量文本
const textMetrics = ctx.measureText('text3');
const width = ctx.measureText(text3).width /2;
// 获取文本高度
const height = textMetrics.actualBoundingBoxAscent + textMetrics.actualBoundingBoxDescent;
drawArcTo (ctx, 24, y- (height / 2), width, radius, 'red')
function drawArcTo (ctx, startXX, startYY, w, r, color) {
let startX = startXX
let startY = startYY
// w = w -10
let x = parseFloat(startX + '')
let y = parseFloat(startY + '')
let endX = x + w + 2 * r + 15
// let endX = w
console.log('endX', endX, x + w)
// let endX = x + w + 2 * r + 15
// if (endX > 700) {
// y += 2 * r + 16
// x = 74
// endX = w
// // endX = x + w + 2 * r + 15
// }
startX = endX
startY = y
// this.list.push(w)
ctx.beginPath()
ctx.moveTo(x + r, y) // 创建开始点
ctx.lineTo(x + w , y) // 创建水平线
ctx.strokeStyle = color
ctx.arcTo(x + w + r, y, x + w + r, y + r, r) // 创建弧
ctx.arcTo(x + w + r, y + (2 * r), x + w, y + (2 * r), r)
ctx.lineTo(x + r, y + (2 * r))
ctx.arcTo(x, y + (2 * r), x, y + r, r)
ctx.arcTo(x, y, x + r, y, r)
// ctx.moveTo(x + r, y) // 创建开始点
// ctx.lineTo(x + w + r, y) // 创建水平线
// ctx.strokeStyle = color
// ctx.arcTo(x + w + 2 * r, y, x + w + 2 * r, y + r, r) // 创建弧
// ctx.arcTo(x + w + 2 * r, y + (2 * r), x + w, y + (2 * r), r)
// ctx.lineTo(x + r, y + (2 * r))
// ctx.arcTo(x, y + (2 * r), x, y + r, r)
// ctx.arcTo(x, y, x + r, y, r)
// ctx.setFillStyle('#2486FF')
ctx.fillStyle = 'white'
ctx.fill()
ctx.stroke();
// console.log()
return [x + r, y + r]
}