1、新建一个工具类文件夹utils
(已有忽略)
2、新建文件common.js
3、在common.js
,新增内容:
export function canvasTextAutoLine(ctx, text, x, y, maxWidth, lineHeight) {
let lineWidth = 0
let lastSubStrIndex = 0
for (let i = 0; i < text.length; i++) {
lineWidth += ctx.measureText(text[i]).width
if (lineWidth > maxWidth) {
ctx.fillText(text.substring(lastSubStrIndex, i), x, y)
y += lineHeight
lineWidth = 0
lastSubStrIndex = i
}
if (i === text.length - 1) {
ctx.fillText(text.substring(lastSubStrIndex, i + 1), x, y)
}
}
}
4、在视图/组件内使用
<script>
import { canvasTextAutoLine } from '@/utils/common'
export default {
methods:{
handleInitCanvas(){
const ctx = uni.createCanvasContext('canvas', this)
...
canvasTextAutoLine(
ctx,
'测试换行文字文字文字文字',
x,
y,
500,
30
)
...
}
}
}
</script>