> 文档中心 > HarmonyOS鸿蒙学习笔记(16)Canvas入门使用

HarmonyOS鸿蒙学习笔记(16)Canvas入门使用

Canvas入门指南

  • 1、Canvas代码结构
  • 2、简单案例
    • 2.1 fillStyle和fillRect 绘制蓝色矩形
    • 2.2 strokeRect和strokeStyle 绘制红色边框
    • 2.3 lineCap的使用
    • 2.4 lineJoin的使用
    • 2.5 closePath的使用
  • 3、参考资料

1、Canvas代码结构

在使用Canvas的时候,需要向初始化RenderingContextSettingsCanvasRenderingContext2D 两个组件,通过CanvasRenderingContext2D 提供的API来进行绘制。Canvas提供了onReady方法,可以在该方法里完成图形的绘制.

 @Entry@Componentstruct 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)//传context给Canvas .width('100%') .height('100%')// .aspectRatio(2.0) .backgroundColor('#ffffff') .onReady(() =>{ })    }    .width('100%')    .height('100%')  }}

2、简单案例

2.1 fillStyle和fillRect 绘制蓝色矩形

  //注意context为CanvasRenderingContext2D对象   this.context.fillStyle = '#0000ff'//填充蓝色  this.context.fillRect(100,200,100,100)

在这里插入图片描述

2.2 strokeRect和strokeStyle 绘制红色边框

  //红色边框 this.context.strokeStyle = '#ff0000'  //边框宽度  this.context.lineWidth = 5  this.context.strokeRect(100, 400, 100, 100)

在这里插入图片描述

2.3 lineCap的使用

指定线端点的样式,可选值为:

  • ‘butt’:线端点以方形结束。
  • ‘round’:线端点以圆形结束。
  • ‘square’:线端点以方形结束,该样式下会增加一个长度和线段厚度相同,宽度是线段厚度一半的矩形。
    默认值:‘butt’。
    lineCap属性有三个值:round、butt、square,其使用方法如下:
 this.context.strokeStyle = '#00ff00'  this.context.lineWidth = 10  this.context.beginPath()  this.context.lineCap = 'round'  this.context.moveTo(100, 100)  this.context.lineTo(200, 100)  this.context.stroke()

round、butt、square效果如果:从上到下依次是round、butt、square
在这里插入图片描述

2.4 lineJoin的使用

指定线段间相交的交点样式,可选值为:

  • ‘round’:在线段相连处绘制一个扇形,扇形的圆角半径是线段的宽度。
  • ‘bevel’:在线段相连处使用三角形为底填充, 每个部分矩形拐角独立。
  • ‘miter’:在相连部分的外边缘处进行延伸,使其相交于一点,形成一个菱形区域,该属性可以通过设置miterLimit属性展现效果。
    默认值:‘miter’。
 this.context.strokeStyle = '#ff0000'  this.context.beginPath()  this.context.lineWidth = 8  this.context.lineJoin = 'miter'  this.context.moveTo(30, 30)  this.context.lineTo(120, 60)  this.context.lineTo(30, 110)  this.context.stroke()

miter,round,bevel效果依次如下:
在这里插入图片描述

2.5 closePath的使用

closePath结束当前路径形成一个封闭路径。

  this.context.strokeStyle = '#00ff00' //创建一个新的绘制路径。   this.context.beginPath()   this.context.lineWidth = 8   this.context.lineJoin = 'round'   //路径从当前点移动到指定点。   this.context.moveTo(130, 30)   //从当前点到指定点进行路径连接。   this.context.lineTo(220, 60)   this.context.lineTo(130, 110)   //进行边框绘制操作。   this.context.closePath()   this.context.stroke()

效果如下:
在这里插入图片描述
当然还有其他很丰富的用法,可以参考官方资料

3、参考资料

Canvas官方文档