font 、 textAlign 、 textBaseline
font
代码
@Entry
@Component
struct Fonts {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.context.font = '30px sans-serif'
this.context.fillText("Hello World", 20, 60)
})
}
.width('100%')
.height('100%')
}
}
效果
textAlign
代码
@Entry
@Component
struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.context.strokeStyle = '#0000ff'
this.context.moveTo(140, 10)
this.context.lineTo(140, 160)
this.context.stroke()
this.context.font = '18px sans-serif'
this.context.textAlign = 'start'
this.context.fillText('textAlign=start', 140, 60)
this.context.textAlign = 'end'
this.context.fillText('textAlign=end', 140, 80)
this.context.textAlign = 'left'
this.context.fillText('textAlign=left', 140, 100)
this.context.textAlign = 'center'
this.context.fillText('textAlign=center',140, 120)
this.context.textAlign = 'right'
this.context.fillText('textAlign=right',140, 140)
})
}
.width('100%')
.height('100%')
}
}
效果
textBaseline
代码
@Entry
@Component
struct TextBaseline {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.context.strokeStyle = '#0000ff'
this.context.moveTo(0, 120)
this.context.lineTo(400, 120)
this.context.stroke()
this.context.font = '20px sans-serif'
this.context.textBaseline = 'top'
this.context.fillText('Top', 10, 120)
this.context.textBaseline = 'bottom'
this.context.fillText('Bottom', 55, 120)
this.context.textBaseline = 'middle'
this.context.fillText('Middle', 125, 120)
this.context.textBaseline = 'alphabetic'
this.context.fillText('Alphabetic', 195, 120)
this.context.textBaseline = 'hanging'
this.context.fillText('Hanging', 295, 120)
})
}
.width('100%')
.height('100%')
}
}
效果