Canvas的渣渣API不支持自动换行和竖排,找了一下没有满意的解决方案,只好自己写一个了。
方法1:根据文字尺寸计算在哪换行
// 画个框用来调试
const DEBUG = true
// 画文本,支持多行、自动换行、竖排文字
function drawText (ctx, text, x, y, width, height, hasStroke = false, isVertical = false) {
if (DEBUG) {
let [oldLineWidth, oldStrokeStyle] = [ctx.lineWidth, ctx.strokeStyle];
[ctx.lineWidth, ctx.strokeStyle] = [1, 'red']
ctx.strokeRect(x, y, width, height);
[ctx.lineWidth, ctx.strokeStyle] = [oldLineWidth, oldStrokeStyle]
}
if (!isVertical) {
drawTextHorizontal(ctx, text, x, y, width, height, hasStroke)
} else {
drawTextVertical(ctx, text, x, y, width, height, hasStroke)
}
}
// 画横排文本,垂直居中,可以垂直溢出
function drawTextHorizontal (ctx, text, x, y, width, height, hasStroke = false) {
let oldBaseLine = ctx.textBaseline
ctx.textBaseline = 'hanging'
let lineHeight = parseInt(ctx.font) // ctx.font必须以'XXpx'开头
// 计算每一行
let lines = []
let curLine = ''
for (let char of text) {
let nextLine = curLine + char
if (char === '\n' || ctx.measureText(nextLine).width > width) {
lines.push(curLine)
curLine = char === '\n' ? '' : char
} else {
curLine = nextLine
}
}
lines.push(curLine)
// 逐行画文本
let lineY = y + (height - lineHeight * lines.length) / 2
for (