加入下方官方优快云班级,得鸿蒙礼盒
本期活动时间:2025年8月1日-12月31日
问题现象
利用Canvas绘制矩形和文字,矩形无法覆盖文字范围。
问题代码示例参考如下:
@Entry
@Component
struct CanvasTestPage {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
drawText: string = 'Harmony你好\n测试一下换行的测试一下换行\n测试制表\t哈哈'
build() {
Column() {
Canvas(this.context)
.width('100%')
.height('100%')
.onReady(() => {
this.context.font = '18vp sans-serif'
let text: TextMetrics = this.context.measureText(this.drawText)
this.context.fillStyle = 'rgba(0,0,0,0.3)'
this.context.fillRect(0, 100, text.width, text.height)
this.context.fillStyle = 'rgb(0,0,255)'
this.context.fillText(this.drawText, 0, 100 + text.height)
})
}.margin(10)
}
}
效果如下:

背景知识
- fillRect:填充一个矩形,四个必填参数依次为矩形左上角点的x坐标、矩形左上角点的y坐标、指定矩形的宽度、指定矩形的高度,根据四个参数即可完成一个矩形的绘制。
- fillText:填充文本,三个必填参数依次为文本内容、文本绘制起点的x轴坐标、文本绘制起点的y轴坐标,根据三个参数即可确定填充文本的坐标。
问题定位
根据问题代码运行效果可以看出:灰色矩形宽度和文本宽度一致,x轴起点保持一致,但是蓝色文字y轴起点和灰色矩形y轴起点不一致,可以推测问题出现在fillRect绘制的y轴起点有问题。
分析结论
根据fillRect和fillText参数可知,保持矩形左上角点的y坐标和文本绘制起点的y轴坐标一致,即可保持绘制时在同一个y轴起点,而不是上文错误代码:
this.context.fillText(this.drawText, 0, 100 + text.height)
该错误代码设置文本的y轴起点为“100+文本高度”。
修改建议
- 修改fillText的文本起点y轴坐标。
- textBaseline可以设置文本绘制中的水平对齐方式,将其设置成top对齐,实现文本基线在文本块的顶部。若不设置,则默认为alphabetic对齐(按字母对齐)。
.onReady(() => { this.context.font = '18vp sans-serif' this.context.textBaseline = 'top' let text: TextMetrics = this.context.measureText(this.drawText) this.context.fillStyle = 'rgba(0,0,0,0.3)' this.context.fillRect(0, 100, text.width, text.height) this.context.fillStyle = 'rgb(0,0,255)' this.context.fillText(this.drawText, 0, 100) })效果预览:


被折叠的 条评论
为什么被折叠?



