harmony 鸿蒙CanvasRenderingContext2D

2022-08-09 浏览 (1037)

CanvasRenderingContext2D

Use RenderingContext to draw rectangles, text, images, and other objects on a canvas.

NOTE

The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.

APIs

CanvasRenderingContext2D(settings?: RenderingContextSettings)

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDescription
settingsRenderingContextSettingsNoSee RenderingContextSettings.

RenderingContextSettings

RenderingContextSettings(antialias?: boolean)

Configures the settings of a CanvasRenderingContext2D object, including whether to enable antialiasing.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDescription
antialiasbooleanNoWhether to enable antialiasing.
Default value: false

Attributes

NameTypeDescription
fillStylestring |number10+ |CanvasGradient |CanvasPatternStyle to fill an area.
- When the type is string, this attribute indicates the color of the fill area.
Default value: 'black'
- When the type is number, this attribute indicates the color of the fill area.
Default value: '#000000'
- When the type is CanvasGradient, this attribute indicates a gradient object, which is created using the createLinearGradient API.
- When the type is CanvasPattern, this attribute indicates a pattern, which is created using the createPattern API.
Since API version 9, this API is supported in ArkTS widgets.
lineWidthnumberLine width.
Default value: 1(px)
strokeStylestring |number10+ |CanvasGradient |CanvasPatternStroke style.
- When the type is string, this attribute indicates the stroke color.
Default value: 'black'
- When the type is number, this attribute indicates the stroke color.
Default value: '#000000'
- When the type is CanvasGradient, this attribute indicates a gradient object, which is created using the createLinearGradient API.
- When the type is CanvasPattern, this attribute indicates a pattern, which is created using the createPattern API.
Since API version 9, this API is supported in ArkTS widgets.
lineCapCanvasLineCapStyle of the line endpoints. The options are as follows:
- 'butt': The endpoints of the line are squared off.
- 'round': The endpoints of the line are rounded.
- 'square': The endpoints of the line are squared off by adding a box with an equal width and half the height of the line's thickness.
Default value: 'butt'
Since API version 9, this API is supported in ArkTS widgets.
lineJoinCanvasLineJoinStyle of the shape used to join line segments. The options are as follows:
- 'round': The shape used to join line segments is a sector, whose radius at the rounded corner is equal to the line width.
- 'bevel': The shape used to join line segments is a triangle. The rectangular corner of each line is independent.
- 'miter': The shape used to join line segments has a mitered corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in miterLimit.
Default value: 'miter'
Since API version 9, this API is supported in ArkTS widgets.
miterLimitnumberMaximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.
Default value: 10
Since API version 9, this API is supported in ArkTS widgets.
fontstringFont style.
Syntax: ctx.font='font-size font-family'
- (Optional) font-size: font size and line height. The unit can be px or vp.
- (Optional) font-family: font family.
Syntax: ctx.font='font-style font-weight font-size font-family'
- (Optional) font-style: font style. Available values are 'normal' and 'italic'.
- (Optional) font-weight: font weight. Available values are as follows: 'normal', 'bold', 'bolder', 'lighter', '100', '200', '300', '400', '500', '600', '700', '800', '900'.
- (Optional) font-size: font size and line height. The unit must be specified and can be px or vp.
- (Optional) font-family: font family. Available values are 'sans-serif', 'serif', and 'monospace'.
Default value: 'normal normal 14px sans-serif'
Since API version 9, this API is supported in ArkTS widgets.
textAlignCanvasTextAlignText alignment mode. Available values are as follows:
- 'left': The text is left-aligned.
- 'right': The text is right-aligned.
- 'center': The text is center-aligned.
- 'start': The text is aligned with the start bound.
- 'end': The text is aligned with the end bound.
In the ltr layout mode, the value 'start' equals 'left'. In the rtl layout mode, the value 'start' equals 'right'.
Default value: 'left'
Since API version 9, this API is supported in ArkTS widgets.
textBaselineCanvasTextBaselineHorizontal alignment mode of text. Available values are as follows:
- 'alphabetic': The text baseline is the normal alphabetic baseline.
- 'top': The text baseline is on the top of the text bounding box.
- 'hanging': The text baseline is a hanging baseline over the text.
- 'middle': The text baseline is in the middle of the text bounding box.
'ideographic': The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.
- 'bottom': The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.
Default value: 'alphabetic'
Since API version 9, this API is supported in ArkTS widgets.
globalAlphanumberOpacity.
0.0: completely transparent.
1.0: completely opaque.
Since API version 9, this API is supported in ArkTS widgets.
lineDashOffsetnumberOffset of the dashed line. The precision is float.
Default value: 0.0
Since API version 9, this API is supported in ArkTS widgets.
globalCompositeOperationstringComposition operation type. Available values are as follows: 'source-over', 'source-atop', 'source-in', 'source-out', 'destination-over', 'destination-atop', 'destination-in', 'destination-out', 'lighter', 'copy', and 'xor'.
Default value: 'source-over'
Since API version 9, this API is supported in ArkTS widgets.
shadowBlurnumberBlur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.
Default value: 0.0
Since API version 9, this API is supported in ArkTS widgets.
shadowColorstringShadow color.
Since API version 9, this API is supported in ArkTS widgets.
shadowOffsetXnumberX-axis shadow offset relative to the original object.
Since API version 9, this API is supported in ArkTS widgets.
shadowOffsetYnumberY-axis shadow offset relative to the original object.
Since API version 9, this API is supported in ArkTS widgets.
imageSmoothingEnabledbooleanWhether to adjust the image smoothness during image drawing. The value true means to enable this feature, and false means the opposite.
Default value: true
Since API version 9, this API is supported in ArkTS widgets.
heightnumberComponent height.
Unit: vp
Since API version 9, this API is supported in ArkTS widgets.
widthnumberComponent width.
Unit: vp
Since API version 9, this API is supported in ArkTS widgets.
imageSmoothingQualityImageSmoothingQualityQuality of image smoothing. This attribute works only when imageSmoothingEnabled is set to true.
Default value: ImageSmoothingQuality.low
Since API version 9, this API is supported in ArkTS widgets.
directionCanvasDirectionText direction used for drawing text.
Default value: CanvasDirection.inherit
Since API version 9, this API is supported in ArkTS widgets.
filterstringFilter effect. Available values are as follows:
- 'none': no filter effect.
- 'blur': applies the Gaussian blur for the image.
- 'brightness': applies a linear multiplication to the image to make it look brighter or darker.
- 'contrast': adjusts the image contrast.
- 'grayscale': converts the image to a grayscale image.
- 'hue-rotate': applies hue rotation to the image.
- 'invert': inverts the input image.
- 'opacity': sets the opacity of the image.
- 'saturate': sets the saturation of the image.
- 'sepia': converts the image to dark brown.
Default value: 'none'
Since API version 9, this API is supported in ArkTS widgets.

NOTE

The string-type value of fillStyle, shadowColor, and strokeStyle can be in 'rgb(255, 255, 255)', 'rgba(255, 255, 255, 1.0)', or '#FFFFFF' format.

fillStyle

// xxx.ets
@Entry
@Component
struct FillStyleExample {
  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.fillStyle = '#0000ff'
          this.context.fillRect(20, 20, 150, 100)
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001257058395

lineWidth

// xxx.ets
@Entry
@Component
struct LineWidthExample {
  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.lineWidth = 5
        this.context.strokeRect(25, 25, 85, 105)
      })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001212378408

strokeStyle

// xxx.ets
@Entry
@Component
struct StrokeStyleExample {
  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.lineWidth = 10
          this.context.strokeStyle = '#0000ff'
          this.context.strokeRect(25, 25, 155, 105)
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001212218446

lineCap

// xxx.ets
@Entry
@Component
struct LineCapExample {
  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.lineWidth = 8
          this.context.beginPath()
          this.context.lineCap = 'round'
          this.context.moveTo(30, 50)
          this.context.lineTo(220, 50)
          this.context.stroke()
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001212378406

lineJoin

// xxx.ets
@Entry
@Component
struct LineJoinExample {
  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.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()
      })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001212218438

miterLimit

// xxx.ets
@Entry
@Component
struct MiterLimit {
  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.lineWidth = 8
          this.context.lineJoin = 'miter'
          this.context.miterLimit = 3
          this.context.moveTo(30, 30)
          this.context.lineTo(60, 35)
          this.context.lineTo(30, 37)
          this.context.stroke()
      })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001212378398

font

// xxx.ets
@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 px", 20, 60)
          this.context.font = '30vp sans-serif'
          this.context.fillText("Hello vp", 20, 100)
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001257058409

textAlign

// xxx.ets
@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%')
  }
}

en-us_image_0000001256978351

textBaseline

// xxx.ets
@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%')
  }
}

en-us_image_0000001212058462

globalAlpha

// xxx.ets
@Entry
@Component
struct GlobalAlpha {
  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.fillStyle = 'rgb(0,0,255)'
          this.context.fillRect(0, 0, 50, 50)
          this.context.globalAlpha = 0.4
          this.context.fillStyle = 'rgb(0,0,255)'
          this.context.fillRect(50, 50, 50, 50)
      })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001194192434

lineDashOffset

// xxx.ets
@Entry
@Component
struct LineDashOffset {
  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.arc(100, 75, 50, 0, 6.28)
          this.context.setLineDash([10,20])
          this.context.lineDashOffset = 10.0
          this.context.stroke()
      })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001194352434

globalCompositeOperation

NameDescription
source-overDisplays the new drawing above the existing drawing. This attribute is used by default.
source-atopDisplays the new drawing on the top of the existing drawing.
source-inDisplays the new drawing inside the existing drawing.
source-outDisplays part of the new drawing that is outside of the existing drawing.
destination-overDisplays the existing drawing above the new drawing.
destination-atopDisplays the existing drawing on the top of the new drawing.
destination-inDisplays the existing drawing inside the new drawing.
destination-outDisplays the existing drawing outside the new drawing.
lighterDisplays both the new and existing drawing.
copyDisplays the new drawing and neglects the existing drawing.
xorCombines the new drawing and existing drawing using the XOR operation.
// xxx.ets
@Entry
@Component
struct GlobalCompositeOperation {
  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.fillStyle = 'rgb(255,0,0)'
          this.context.fillRect(20, 20, 50, 50)
          this.context.globalCompositeOperation = 'source-over'
          this.context.fillStyle = 'rgb(0,0,255)'
          this.context.fillRect(50, 50, 50, 50)
          this.context.fillStyle = 'rgb(255,0,0)'
          this.context.fillRect(120, 20, 50, 50)
          this.context.globalCompositeOperation = 'destination-over'
          this.context.fillStyle = 'rgb(0,0,255)'
          this.context.fillRect(150, 50, 50, 50)
      })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001211898480

shadowBlur

// xxx.ets
@Entry
@Component
struct ShadowBlur {
  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.shadowBlur = 30
          this.context.shadowColor = 'rgb(0,0,0)'
          this.context.fillStyle = 'rgb(255,0,0)'
          this.context.fillRect(20, 20, 100, 80)
      })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001256978343

shadowColor

// xxx.ets
@Entry
@Component
struct ShadowColor {
  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.shadowBlur = 30
          this.context.shadowColor = 'rgb(0,0,255)'
          this.context.fillStyle = 'rgb(255,0,0)'
          this.context.fillRect(30, 30, 100, 100)
      })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001257138353

shadowOffsetX

// xxx.ets
@Entry
@Component
struct ShadowOffsetX {
  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.shadowBlur = 10
          this.context.shadowOffsetX = 20
          this.context.shadowColor = 'rgb(0,0,0)'
          this.context.fillStyle = 'rgb(255,0,0)'
          this.context.fillRect(20, 20, 100, 80)
      })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001212218436

shadowOffsetY

// xxx.ets
@Entry
@Component
struct ShadowOffsetY {
  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.shadowBlur = 10
          this.context.shadowOffsetY = 20
          this.context.shadowColor = 'rgb(0,0,0)'
          this.context.fillStyle = 'rgb(255,0,0)'
          this.context.fillRect(30, 30, 100, 100)
      })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001212378410

imageSmoothingEnabled

// xxx.ets
@Entry
@Component
struct ImageSmoothingEnabled {
  private settings: RenderingContextSettings = new RenderingContextSettings(true)
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg")
  
  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
      Canvas(this.context)
        .width('100%')
        .height('100%')
        .backgroundColor('#ffff00')
        .onReady(() =>{
          this.context.imageSmoothingEnabled = false
          this.context.drawImage( this.img,0,0,400,200)
      })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001211898472

height

// xxx.ets
@Entry
@Component
struct HeightExample {
  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(300)
        .height(300)
        .backgroundColor('#ffff00')
        .onReady(() => {
          let h = this.context.height
          let w = this.context.width
          this.context.fillRect(0, 0, 300, h/2)
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_canvas_height

width

// xxx.ets
@Entry
@Component
struct WidthExample {
  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(300)
        .height(300)
        .backgroundColor('#ffff00')
        .onReady(() => {
          let h = this.context.height
          let w = this.context.width
          this.context.fillRect(0, 0, w/2, 300)
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_canvas_width

imageSmoothingQuality

  // xxx.ets
  @Entry
  @Component
  struct ImageSmoothingQualityDemo {
    private settings: RenderingContextSettings = new RenderingContextSettings(true);
    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
    private img:ImageBitmap = new ImageBitmap("common/images/example.jpg");

    build() {
      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
        Canvas(this.context)
          .width('100%')
          .height('100%')
          .backgroundColor('#ffff00')
          .onReady(() =>{
            let ctx = this.context
            ctx.imageSmoothingEnabled = true
            ctx.imageSmoothingQuality = 'high'
            ctx.drawImage(this.img, 0, 0, 400, 200)
          })
      }
      .width('100%')
      .height('100%')
    }
  }

ImageSmoothingQualityDemo

direction

  // xxx.ets
  @Entry
  @Component
  struct DirectionDemo {
    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(() =>{
            let ctx = this.context
            ctx.font = '48px serif';
            ctx.textAlign = 'start'
            ctx.fillText("Hi ltr!", 200, 50);

            ctx.direction = "rtl";
            ctx.fillText("Hi rtl!", 200, 100);
          })
      }
      .width('100%')
      .height('100%')
    }
  }

directionDemo

filter

  // xxx.ets
  @Entry
  @Component
  struct FilterDemo {
    private settings: RenderingContextSettings = new RenderingContextSettings(true);
    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
    private img:ImageBitmap = new ImageBitmap("common/images/example.jpg");

    build() {
      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
        Canvas(this.context)
          .width('100%')
          .height('100%')
          .backgroundColor('#ffff00')
          .onReady(() =>{
            let ctx = this.context
            let img = this.img

            ctx.drawImage(img, 0, 0, 100, 100);

            ctx.filter = 'grayscale(50%)';
            ctx.drawImage(img, 100, 0, 100, 100);

            ctx.filter = 'sepia(60%)';
            ctx.drawImage(img, 200, 0, 100, 100);

            ctx.filter = 'saturate(30%)';
            ctx.drawImage(img, 0, 100, 100, 100);

            ctx.filter = 'hue-rotate(90degree)';
            ctx.drawImage(img, 100, 100, 100, 100);

            ctx.filter = 'invert(100%)';
            ctx.drawImage(img, 200, 100, 100, 100);

            ctx.filter = 'opacity(25%)';
            ctx.drawImage(img, 0, 200, 100, 100);

            ctx.filter = 'brightness(0.4)';
            ctx.drawImage(img, 100, 200, 100, 100);

            ctx.filter = 'contrast(200%)';
            ctx.drawImage(img, 200, 200, 100, 100);

            ctx.filter = 'blur(5px)';
            ctx.drawImage(img, 0, 300, 100, 100);

            let result = ctx.toDataURL()
            console.info(result)
          })
      }
      .width('100%')
      .height('100%')
    }
  }

filterDemo

Methods

fillRect

fillRect(x: number, y: number, w: number, h: number): void

Fills a rectangle on the canvas.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
xnumberYes0X coordinate of the upper left corner of the rectangle.
ynumberYes0Y coordinate of the upper left corner of the rectangle.
widthnumberYes0Width of the rectangle.
heightnumberYes0Height of the rectangle.

Example

// xxx.ets
@Entry
@Component
struct FillRect {
  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.fillRect(30,30,100,100)
       })
      }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001212218440

strokeRect

strokeRect(x: number, y: number, w: number, h: number): void

Draws an outlined rectangle on the canvas.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
xnumberYes0X coordinate of the upper left corner of the rectangle.
ynumberYes0Y coordinate of the upper left corner of the rectangle.
wnumberYes0Width of the rectangle.
hnumberYes0Height of the rectangle.

Example

// xxx.ets
@Entry
@Component
struct StrokeRect {
  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.strokeRect(30, 30, 200, 150)
      })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001257138359

clearRect

clearRect(x: number, y: number, w: number, h: number): void

Clears the content in a rectangle on the canvas.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
xnumberYes0X coordinate of the upper left corner of the rectangle.
ynumberYes0Y coordinate of the upper left corner of the rectangle.
wnumberYes0Width of the rectangle.
hnumberYes0Height of the rectangle.

Example

// xxx.ets
@Entry
@Component
struct ClearRect {
  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.fillStyle = 'rgb(0,0,255)'
          this.context.fillRect(20,20,200,200)
          this.context.clearRect(30,30,150,100)
      })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001211898482

fillText

fillText(text: string, x: number, y: number, maxWidth?: number): void

Draws filled text on the canvas.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
textstringYes''Text to draw.
xnumberYes0X coordinate of the lower left corner of the text.
ynumberYes0Y coordinate of the lower left corner of the text.
maxWidthnumberNo-Maximum width allowed for the text.

Example

// xxx.ets
@Entry
@Component
struct FillText {
  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, 100)
      })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001257058399

strokeText

strokeText(text: string, x: number, y: number, maxWidth?:number): void

Draws a text stroke on the canvas.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
textstringYes''Text to draw.
xnumberYes0X coordinate of the lower left corner of the text.
ynumberYes0Y coordinate of the lower left corner of the text.
maxWidthnumberNo-Maximum width of the text to be drawn.

Example

// xxx.ets
@Entry
@Component
struct StrokeText {
  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 = '55px sans-serif'
          this.context.strokeText("Hello World!", 20, 60)
      })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001256978349

measureText

measureText(text: string): TextMetrics

Measures the specified text to obtain its width. This API returns a TextMetrics object.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
textstringYes''Text to be measured.

Return value

TypeDescription
TextMetricsTextMetrics object.
Since API version 9, this API is supported in ArkTS widgets.

TextMetrics

AttributeTypeDescription
widthnumberWidth of the text.
heightnumberHeight of the text.
actualBoundingBoxAscentnumberDistance from the horizontal line specified by the CanvasRenderingContext2D.textBaseline attribute to the top of the bounding rectangle used to render the text. The current value is 0.
actualBoundingBoxDescentnumberDistance from the horizontal line specified by the CanvasRenderingContext2D.textBaseline attribute to the bottom of the bounding rectangle used to render the text. The current value is 0.
actualBoundingBoxLeftnumberDistance parallel to the baseline from the alignment point determined by the CanvasRenderingContext2D.textAlign attribute to the left side of the bounding rectangle of the text. The current value is 0.
actualBoundingBoxRightnumberDistance parallel to the baseline from the alignment point determined by the CanvasRenderingContext2D.textAlign attribute to the right side of the bounding rectangle of the text. The current value is 0.
alphabeticBaselinenumberDistance from the horizontal line specified by the CanvasRenderingContext2D.textBaseline attribute to the alphabetic baseline of the line box. The current value is 0.
emHeightAscentnumberDistance from the horizontal line specified by the CanvasRenderingContext2D.textBaseline attribute to the top of the em square in the line box. The current value is 0.
emHeightDescentnumberDistance from the horizontal line specified by the CanvasRenderingContext2D.textBaseline attribute to the bottom of the em square in the line box. The current value is 0.
fontBoundingBoxAscentnumberDistance from the horizontal line specified by the CanvasRenderingContext2D.textBaseline attribute to the top of the highest bounding rectangle of all the fonts used to render the text. The current value is 0.
fontBoundingBoxDescentnumberDistance from the horizontal line specified by the CanvasRenderingContext2D.textBaseline attribute to the bottom of the bounding rectangle of all the fonts used to render the text. The current value is 0.
hangingBaselinenumberDistance from the horizontal line specified by the CanvasRenderingContext2D.textBaseline attribute to the hanging baseline of the line box. The current value is 0.
ideographicBaselinenumberDistance from the horizontal line indicated by the CanvasRenderingContext2D.textBaseline attribute to the ideographic baseline of the line box. The current value is 0.

Example

// xxx.ets
@Entry
@Component
struct MeasureText {
  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 = '50px sans-serif'
          this.context.fillText("Hello World!", 20, 100)
          this.context.fillText("width:" + this.context.measureText("Hello World!").width, 20, 200)
      })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001257138343

stroke

stroke(path?: Path2D): void

Strokes a path.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
pathPath2DNonullA Path2D path to draw.

Example

// xxx.ets
@Entry
@Component
struct Stroke {
  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.moveTo(25, 25)
          this.context.lineTo(25, 105)
          this.context.lineTo(75, 105)
          this.context.lineTo(75, 25)
          this.context.strokeStyle = 'rgb(0,0,255)'
          this.context.stroke()
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001257058411

beginPath

beginPath(): void

Creates a drawing path.

Since API version 9, this API is supported in ArkTS widgets.

Example

// xxx.ets
@Entry
@Component
struct BeginPath {
  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.beginPath()
          this.context.lineWidth = 6
          this.context.strokeStyle = '#0000ff'
          this.context.moveTo(15, 80)
          this.context.lineTo(280, 160)
          this.context.stroke()
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001212058478

moveTo

moveTo(x: number, y: number): void

Moves a drawing path to a target position on the canvas.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
xnumberYes0X coordinate of the target position.
ynumberYes0Y coordinate of the target position.

Example

// xxx.ets
@Entry
@Component
struct MoveTo {
  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.beginPath()
          this.context.moveTo(10, 10)
          this.context.lineTo(280, 160)
          this.context.stroke()
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001256858391

lineTo

lineTo(x: number, y: number): void

Connects the current point to a target position using a straight line.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
xnumberYes0X coordinate of the target position.
ynumberYes0Y coordinate of the target position.

Example

// xxx.ets
@Entry
@Component
struct LineTo {
  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.beginPath()
          this.context.moveTo(10, 10)
          this.context.lineTo(280, 160)
          this.context.stroke()
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001212378414

closePath

closePath(): void

Draws a closed path.

Since API version 9, this API is supported in ArkTS widgets.

Example

// xxx.ets
@Entry
@Component
struct ClosePath {
  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.beginPath()
            this.context.moveTo(30, 30)
            this.context.lineTo(110, 30)
            this.context.lineTo(70, 90)
            this.context.closePath()
            this.context.stroke()
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001256978347

createPattern

createPattern(image: ImageBitmap, repetition: string|null): CanvasPattern|null

Creates a pattern for image filling based on a specified source image and repetition mode.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDescription
imageImageBitmapYesSource image. For details, see ImageBitmap.
repetitionstringYesRepetition mode. The value can be 'repeat', 'repeat-x', 'repeat-y', 'no-repeat', 'clamp', or 'mirror'.
Default value: ''

Return value

TypeDescription
CanvasPatternCreated pattern for image filling based on a specified source image and repetition mode.

Example

// xxx.ets
@Entry
@Component
struct CreatePattern {
  private settings: RenderingContextSettings = new RenderingContextSettings(true)
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg")

  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
      Canvas(this.context)
        .width('100%')
        .height('100%')
        .backgroundColor('#ffff00')
        .onReady(() =>{
          let pattern = this.context.createPattern(this.img, 'repeat')
          if (pattern) {
            this.context.fillStyle = pattern
          }
          this.context.fillRect(0, 0, 200, 200)
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001211898490

bezierCurveTo

bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void

Draws a cubic bezier curve on the canvas.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
cp1xnumberYes0X coordinate of the first parameter of the bezier curve.
cp1ynumberYes0Y coordinate of the first parameter of the bezier curve.
cp2xnumberYes0X coordinate of the second parameter of the bezier curve.
cp2ynumberYes0Y coordinate of the second parameter of the bezier curve.
xnumberYes0X coordinate of the end point on the bezier curve.
ynumberYes0Y coordinate of the end point on the bezier curve.

Example

// xxx.ets
@Entry
@Component
struct BezierCurveTo {
  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.beginPath()
          this.context.moveTo(10, 10)
          this.context.bezierCurveTo(20, 100, 200, 100, 200, 20)
          this.context.stroke()
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001257138349

quadraticCurveTo

quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void

Draws a quadratic curve on the canvas.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
cpxnumberYes0X coordinate of the bezier curve parameter.
cpynumberYes0Y coordinate of the bezier curve parameter.
xnumberYes0X coordinate of the end point on the bezier curve.
ynumberYes0Y coordinate of the end point on the bezier curve.

Example

// xxx.ets
@Entry
@Component
struct QuadraticCurveTo {
  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.beginPath()
          this.context.moveTo(20, 20)
          this.context.quadraticCurveTo(100, 100, 200, 20)
          this.context.stroke()
      })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001257058397

arc

arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void

Draws an arc on the canvas.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
xnumberYes0X coordinate of the center point of the arc.
ynumberYes0Y coordinate of the center point of the arc.
radiusnumberYes0Radius of the arc.
startAnglenumberYes0Start radian of the arc.
endAnglenumberYes0End radian of the arc.
counterclockwisebooleanNofalseWhether to draw the arc counterclockwise.

Example

// xxx.ets
@Entry
@Component
struct Arc {
  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.beginPath()
          this.context.arc(100, 75, 50, 0, 6.28)
          this.context.stroke()
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001212378404

arcTo

arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void

Draws an arc based on the radius and points on the arc.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
x1numberYes0X coordinate of the first point on the arc.
y1numberYes0Y coordinate of the first point on the arc.
x2numberYes0X coordinate of the second point on the arc.
y2numberYes0Y coordinate of the second point on the arc.
radiusnumberYes0Radius of the arc.

Example

// xxx.ets
@Entry
@Component
struct ArcTo {
  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.moveTo(100, 20)
          this.context.arcTo(150, 20, 150, 70, 50)
          this.context.stroke()
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001257058413

ellipse

ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void

Draws an ellipse in the specified rectangular region on the canvas.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
xnumberYes0X coordinate of the ellipse center.
ynumberYes0Y coordinate of the ellipse center.
radiusXnumberYes0Ellipse radius on the x-axis.
radiusYnumberYes0Ellipse radius on the y-axis.
rotationnumberYes0Rotation angle of the ellipse. The unit is radian.
startAnglenumberYes0Angle of the start point for drawing the ellipse. The unit is radian.
endAnglenumberYes0Angle of the end point for drawing the ellipse. The unit is radian.
counterclockwisebooleanNofalseWhether to draw the ellipse in the counterclockwise direction.
true: Draw the arc counterclockwise.
false: Draw the arc clockwise.

Example

// xxx.ets
@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.beginPath()
          this.context.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI * 2)
          this.context.stroke()
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001256978339

rect

rect(x: number, y: number, w: number, h: number): void

Creates a rectangle on the canvas.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
xnumberYes0X coordinate of the upper left corner of the rectangle.
ynumberYes0Y coordinate of the upper left corner of the rectangle.
wnumberYes0Width of the rectangle.
hnumberYes0Height of the rectangle.

Example

// xxx.ets
@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.rect(20, 20, 100, 100) // Create a 100*100 rectangle at (20, 20)
          this.context.stroke()
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001256978341

fill

fill(fillRule?: CanvasFillRule): void

Fills the area inside a closed path on the canvas.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
fillRuleCanvasFillRuleNo"nonzero"Rule by which to determine whether a point is inside or outside the area to fill.
The options are "nonzero" and "evenodd".

Example

// xxx.ets
@Entry
@Component
struct Fill {
  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.rect(20, 20, 100, 100) // Create a 100*100 rectangle at (20, 20)
          this.context.fill()
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001256858389

fill(path: Path2D, fillRule?: CanvasFillRule): void

Fills the area inside a closed path on the canvas.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
pathPath2DYesA Path2D path to fill.
fillRuleCanvasFillRuleNo"nonzero"Rule by which to determine whether a point is inside or outside the area to fill.
The options are "nonzero" and "evenodd".

Example

// xxx.ets
@Entry
@Component
struct Fill {
  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(() =>{
          let region = new Path2D()
          region.moveTo(30, 90)
          region.lineTo(110, 20)
          region.lineTo(240, 130)
          region.lineTo(60, 130)
          region.lineTo(190, 20)
          region.lineTo(270, 90)
          region.closePath()
          // Fill path
          this.context.fillStyle = '#00ff00'
          this.context.fill(region, "evenodd")
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_000000127777774

clip

clip(fillRule?: CanvasFillRule): void

Sets the current path to a clipping area.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
fillRuleCanvasFillRuleNo"nonzero"Rule by which to determine whether a point is inside or outside the area to clip.
The options are "nonzero" and "evenodd".

Example

// xxx.ets
@Entry
@Component
struct Clip {
  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.rect(0, 0, 100, 200)
          this.context.stroke()
          this.context.clip()
          this.context.fillStyle = "rgb(255,0,0)"
          this.context.fillRect(0, 0, 200, 200)
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001211898488

clip(path: Path2D, fillRule?: CanvasFillRule): void

Sets the current path to a clipping path.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
pathPath2DYes-A Path2D path to use as a clipping area.
fillRuleCanvasFillRuleNo"nonzero"Rule by which to determine whether a point is inside or outside the area to clip.
The options are "nonzero" and "evenodd".

Example

// xxx.ets
@Entry
@Component
struct Clip {
  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(() =>{
          let region = new Path2D()
          region.moveTo(30, 90)
          region.lineTo(110, 20)
          region.lineTo(240, 130)
          region.lineTo(60, 130)
          region.lineTo(190, 20)
          region.lineTo(270, 90)
          region.closePath()
          this.context.clip(region,"evenodd")
          this.context.fillStyle = "rgb(0,255,0)"
          this.context.fillRect(0, 0, this.context.width, this.context.height)
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_000000127777779

resetTransform

resetTransform(): void

Resets the current transform to the identity matrix. This API is a void API.

Since API version 9, this API is supported in ArkTS widgets.

rotate

rotate(angle: number): void

Rotates a canvas clockwise around its coordinate axes.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
anglenumberYes0Clockwise rotation angle. You can use Math.PI / 180 to convert the angle to a radian.

Example

// xxx.ets
@Entry
@Component
struct Rotate {
  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.rotate(45 * Math.PI / 180)
          this.context.fillRect(70, 20, 50, 50)
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001212218442

scale

scale(x: number, y: number): void

Scales the canvas based on the given scale factors.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
xnumberYes0Horizontal scale factor.
ynumberYes0Vertical scale factor.

Example

// xxx.ets
@Entry
@Component
struct Scale {
  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.lineWidth = 3
          this.context.strokeRect(30, 30, 50, 50)
          this.context.scale(2, 2) // Scale to 200%
          this.context.strokeRect(30, 30, 50, 50)
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001257138347

transform

transform(a: number, b: number, c: number, d: number, e: number, f: number): void

Defines a transformation matrix. To transform a graph, you only need to set parameters of the matrix. The coordinates of the graph are multiplied by the matrix values to obtain new coordinates of the transformed graph. You can use the matrix to implement multiple transform effects.

Since API version 9, this API is supported in ArkTS widgets.

NOTE

The following formulas calculate coordinates of the transformed graph. x and y represent coordinates before transformation, and x' and y' represent coordinates after transformation.

  • x' = scaleX * x + skewY * y + translateX

  • y' = skewX * x + scaleY * y + translateY

Parameters

NameTypeMandatoryDefault ValueDescription
anumberYes0X-axis scale.
bnumberYes0X-axis skew.
cnumberYes0Y-axis skew.
dnumberYes0Y-axis scale.
enumberYes0X-axis translation.
fnumberYes0Y-axis translation.

Example

// xxx.ets
@Entry
@Component
struct Transform {
  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.fillStyle = 'rgb(0,0,0)'
          this.context.fillRect(0, 0, 100, 100)
          this.context.transform(1, 0.5, -0.5, 1, 10, 10)
          this.context.fillStyle = 'rgb(255,0,0)'
          this.context.fillRect(0, 0, 100, 100)
          this.context.transform(1, 0.5, -0.5, 1, 10, 10)
          this.context.fillStyle = 'rgb(0,0,255)'
          this.context.fillRect(0, 0, 100, 100)
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001256858393

setTransform

setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void

Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the transform() API.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
anumberYes0X-axis scale.
bnumberYes0X-axis skew.
cnumberYes0Y-axis skew.
dnumberYes0Y-axis scale.
enumberYes0X-axis translation.
fnumberYes0Y-axis translation.

Example

// xxx.ets
@Entry
@Component
struct SetTransform {
  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.fillStyle = 'rgb(255,0,0)'
          this.context.fillRect(0, 0, 100, 100)
          this.context.setTransform(1,0.5, -0.5, 1, 10, 10)
          this.context.fillStyle = 'rgb(0,0,255)'
          this.context.fillRect(0, 0, 100, 100)
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001256858395

setTransform

setTransform(transform?: Matrix2D): void

Resets the current transformation to the identity matrix, and then creates a new transformation matrix based on the specified Matrix2D object.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
transformMatrix2DNonullTransformation matrix.

getTransform

getTransform(): Matrix2D

Obtains the current transformation matrix being applied to the context.

Since API version 9, this API is supported in ArkTS widgets.

Return value

TypeDescription
Matrix2DMatrix2D object.

Example

// xxx.ets
@Entry
@Component
struct TransFormDemo {
  private settings: RenderingContextSettings = new RenderingContextSettings(true);
  private context1: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  private context2: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);

  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
      Text('context1');
      Canvas(this.context1)
        .width('230vp')
        .height('120vp')
        .backgroundColor('#ffff00')
        .onReady(() =>{
          this.context1.fillRect(50, 50, 50, 50);
          this.context1.setTransform(1.2, Math.PI/8, Math.PI/6, 0.5, 30, -25);
          this.context1.fillRect(50, 50, 50, 50);
        })
      Text('context2');
      Canvas(this.context2)
        .width('230vp')
        .height('120vp')
        .backgroundColor('#0ffff0')
        .onReady(() =>{
          this.context2.fillRect(50, 50, 50, 50);
          let storedTransform = this.context1.getTransform();
          console.log("Matrix [scaleX = " + storedTransform.scaleX + ", scaleY = " + storedTransform.scaleY +
          ", rotateX = " + storedTransform.rotateX + ", rotateY = " + storedTransform.rotateY +
          ", translateX = " + storedTransform.translateX + ", translateY = " + storedTransform.translateY + "]")
          this.context2.setTransform(storedTransform);
          this.context2.fillRect(50,50,50,50);
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001219982726.png

translate

translate(x: number, y: number): void

Moves the origin of the coordinate system.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
xnumberYes0X-axis translation.
ynumberYes0Y-axis translation.

Example

// xxx.ets
@Entry
@Component
struct Translate {
  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.fillRect(10, 10, 50, 50)
          this.context.translate(70, 70)
          this.context.fillRect(10, 10, 50, 50)
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001257138357

drawImage

drawImage(image: ImageBitmap|PixelMap, dx: number, dy: number): void

drawImage(image: ImageBitmap|PixelMap, dx: number, dy: number, dw: number, dh: number): void

drawImage(image: ImageBitmap|PixelMap, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number):void

Draws an image on the canvas.

Since API version 9, this API is supported in ArkTS widgets, except that PixelMap objects are not supported.

Parameters

NameTypeMandatoryDefault ValueDescription
imageImageBitmap or PixelMapYesnullImage resource. For details, see ImageBitmap or PixelMap.
sxnumberNo0X coordinate of the upper left corner of the rectangle used to crop the source image.
synumberNo0Y coordinate of the upper left corner of the rectangle used to crop the source image.
swnumberNo0Target width to crop the source image.
shnumberNo0Target height to crop the source image.
dxnumberYes0X coordinate of the upper left corner of the drawing area on the canvas.
dynumberYes0Y coordinate of the upper left corner of the drawing area on the canvas.
dwnumberNo0Width of the drawing area. If the width of the drawing area is different from that of the cropped image, the latter will be stretched or compressed to the former.
dhnumberNo0Height of the drawing area. If the height of the drawing area is different from that of the cropped image, the latter will be stretched or compressed to the former.

Example

// xxx.ets
@Entry
@Component
struct ImageExample {
  private settings: RenderingContextSettings = new RenderingContextSettings(true)
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  private img:ImageBitmap = new ImageBitmap("common/images/example.jpg")

  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
      Canvas(this.context)
        .width('100%')
        .height('100%')
        .backgroundColor('#ffff00')
        .onReady(() =>{
          this.context.drawImage( this.img,0,0,500,500,0,0,400,200)
      })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001212058466

createImageData

createImageData(sw: number, sh: number): ImageData

Creates an ImageData object with the specified dimensions.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
swnumberYes0Width of the ImageData object.
shnumberYes0Height of the ImageData object.

createImageData(imageData: ImageData): ImageData

Creates an ImageData object.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
imagedataImageDataYesnullImageData object with the same width and height copied from the original ImageData object.

Return value

TypeDescription
ImageDataNew ImageData object.

getPixelMap

getPixelMap(sx: number, sy: number, sw: number, sh: number): PixelMap

Obtains the PixelMap object created with the pixels within the specified area on the canvas.

Parameters

NameTypeMandatoryDefault ValueDescription
sxnumberYes0X coordinate of the upper left corner of the output area.
synumberYes0Y coordinate of the upper left corner of the output area.
swnumberYes0Width of the output area.
shnumberYes0Height of the output area.

Return value

TypeDescription
PixelMapPixelMap object.

getImageData

getImageData(sx: number, sy: number, sw: number, sh: number): ImageData

Obtains the ImageData object created with the pixels within the specified area on the canvas.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
sxnumberYes0X coordinate of the upper left corner of the output area.
synumberYes0Y coordinate of the upper left corner of the output area.
swnumberYes0Width of the output area.
shnumberYes0Height of the output area.

Return value

TypeDescription
ImageDataNew ImageData object.

Example

// xxx.ets
@Entry
@Component
struct GetImageData {
  private settings: RenderingContextSettings = new RenderingContextSettings(true)
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  private img:ImageBitmap = new ImageBitmap("/common/images/1234.png")

  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
      Canvas(this.context)
        .width('100%')
        .height('100%')
        .backgroundColor('#ffff00')
        .onReady(() =>{
          this.context.drawImage(this.img,0,0,130,130)
          let imagedata = this.context.getImageData(50,50,130,130)
          this.context.putImageData(imagedata,150,150)
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_000000127777780

putImageData

putImageData(imageData: ImageData, dx: number|string, dy: number|string): void

putImageData(imageData: ImageData, dx: number|string, dy: number|string, dirtyX: number|string, dirtyY: number|string, dirtyWidth: number|string, dirtyHeight: number|string): void

Puts an ImageData object onto a rectangular area on the canvas.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
imagedataImageDataYesnullImageData object with pixels to put onto the canvas.
dxnumber |string10+Yes0X-axis offset of the rectangular area on the canvas.
dynumber |string10+Yes0Y-axis offset of the rectangular area on the canvas.
dirtyXnumber |string10+No0X-axis offset of the upper left corner of the rectangular area relative to that of the source image.
dirtyYnumber |string10+No0Y-axis offset of the upper left corner of the rectangular area relative to that of the source image.
dirtyWidthnumber |string10+NoWidth of the ImageData objectWidth of the rectangular area to crop the source image.
dirtyHeightnumber |string10+NoHeight of the ImageData objectHeight of the rectangular area to crop the source image.

Example

// xxx.ets
@Entry
@Component
struct PutImageData {
  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(() =>{
          let imageData = this.context.createImageData(100, 100)
          for (let i = 0; i < imageData.data.length; i += 4) {
            imageData.data[i + 0] = 255
            imageData.data[i + 1] = 0
            imageData.data[i + 2] = 255
            imageData.data[i + 3] = 255
          }
          this.context.putImageData(imageData, 10, 10)
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001212378396

setLineDash

setLineDash(segments: number[]): void

Sets the dash line style.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeDescription
segmentsnumber[]An array of numbers that specify distances to alternately draw a line and a gap.

Example

// xxx.ets
@Entry
@Component
struct SetLineDash {
  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.arc(100, 75, 50, 0, 6.28)
          this.context.setLineDash([10,20])
          this.context.stroke()
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_000000127777771

getLineDash

getLineDash(): number[]

Obtains the dash line style.

Since API version 9, this API is supported in ArkTS widgets.

Return value

TypeDescription
number[]An array of numbers that specify distances to alternately draw a line and a gap.

Example

// xxx.ets
@Entry
@Component
struct CanvasGetLineDash {
  @State message: string = 'Hello World'
  private settings: RenderingContextSettings = new RenderingContextSettings(true)
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(()=>{
            console.error('before getlinedash clicked')
            let res = this.context.getLineDash()
            console.error(JSON.stringify(res))
          })
        Canvas(this.context)
          .width('100%')
          .height('100%')
          .backgroundColor('#ffff00')
          .onReady(() => {
            this.context.arc(100, 75, 50, 0, 6.28)
            this.context.setLineDash([10,20])
            this.context.stroke()
            let res = this.context.getLineDash()
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

en-us_image_000000127777778

transferFromImageBitmap

transferFromImageBitmap(bitmap: ImageBitmap): void

Displays the specified ImageBitmap object.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeDescription
bitmapImageBitmapImageBitmap object to display.

Example

// xxx.ets
@Entry
@Component
struct TransferFromImageBitmap {
  private settings: RenderingContextSettings = new RenderingContextSettings(true)
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)

  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
      Canvas(this.context)
        .width('100%')
        .height('100%')
        .backgroundColor('#ffff00')
        .onReady(() =>{
          let imageData = this.offContext.createImageData(100, 100)
          for (let i = 0; i < imageData.data.length; i += 4) {
            imageData.data[i + 0] = 255
            imageData.data[i + 1] = 0
            imageData.data[i + 2] = 255
            imageData.data[i + 3] = 255
          }
          this.offContext.putImageData(imageData, 10, 10)
          let image = this.offContext.transferToImageBitmap()
          this.context.transferFromImageBitmap(image)
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_000000127777773

toDataURL

toDataURL(type?: string, quality?: number): string

Generates a URL containing image display information.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDescription
typestringNoImage format. The default value is image/png.
qualitynumberNoImage quality, which ranges from 0 to 1, when the image format is image/jpeg or image/webp. If the set value is beyond the value range, the default value 0.92 is used.

Return value

TypeDescription
stringImage URL.

Example

// xxx.ets
@Entry
@Component
struct ToDataURL {
  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(() =>{
          let dataURL = this.context.toDataURL()
        })
    }
    .width('100%')
    .height('100%')
  }
}

restore

restore(): void

Restores the saved drawing context.

Since API version 9, this API is supported in ArkTS widgets.

Example

// xxx.ets
@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.save() // save the default state
          this.context.fillStyle = "#00ff00"
          this.context.fillRect(20, 20, 100, 100)
          this.context.restore() // restore to the default state
          this.context.fillRect(150, 75, 100, 100)
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_000000127777781

save

save(): void

Saves all states of the canvas in the stack. This API is usually called when the drawing state needs to be saved.

Since API version 9, this API is supported in ArkTS widgets.

Example

// xxx.ets
@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.save() // save the default state
          this.context.fillStyle = "#00ff00"
          this.context.fillRect(20, 20, 100, 100)
          this.context.restore() // restore to the default state
          this.context.fillRect(150, 75, 100, 100)
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_000000127777781

createLinearGradient

createLinearGradient(x0: number, y0: number, x1: number, y1: number): void

Creates a linear gradient.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
x0numberYes0X coordinate of the start point.
y0numberYes0Y coordinate of the start point.
x1numberYes0X coordinate of the end point.
y1numberYes0Y coordinate of the end point.

Example

// xxx.ets
@Entry
@Component
struct CreateLinearGradient {
  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(() =>{
          let grad = this.context.createLinearGradient(50,0, 300,100)
          grad.addColorStop(0.0, '#ff0000')
          grad.addColorStop(0.5, '#ffffff')
          grad.addColorStop(1.0, '#00ff00')
          this.context.fillStyle = grad
          this.context.fillRect(0, 0, 400, 400)
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001212378412

createRadialGradient

createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): void

Creates a linear gradient.

Since API version 9, this API is supported in ArkTS widgets.

Parameters

NameTypeMandatoryDefault ValueDescription
x0numberYes0X coordinate of the center of the start circle.
y0numberYes0Y coordinate of the center of the start circle.
r0numberYes0Radius of the start circle, which must be a non-negative finite number.
x1numberYes0X coordinate of the center of the end circle.
y1numberYes0Y coordinate of the center of the end circle.
r1numberYes0Radius of the end circle, which must be a non-negative finite number.

Example

// xxx.ets
@Entry
@Component
struct CreateRadialGradient {
  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(() =>{
          let grad = this.context.createRadialGradient(200,200,50, 200,200,200)
          grad.addColorStop(0.0, '#ff0000')
          grad.addColorStop(0.5, '#ffffff')
          grad.addColorStop(1.0, '#00ff00')
          this.context.fillStyle = grad
          this.context.fillRect(0, 0, 440, 440)
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001257058405

createConicGradient10+

createConicGradient(startAngle: number, x: number, y: number): CanvasGradient

Creates a conic gradient.

Parameters

NameTypeMandatoryDefault ValueDescription
startAnglenumberYes0Angle at which the gradient starts, in radians. The angle measurement starts horizontally from the right side of the center and moves clockwise.
xnumberYes0X coordinate of the center of the conic gradient, in vp.
ynumberYes0Y coordinate of the center of the conic gradient, in vp.

Example

// xxx.ets
@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('#ffffff')
        .onReady(() => {
          let grad = this.context.createConicGradient(0, 50, 80)
          grad.addColorStop(0.0, '#ff0000')
          grad.addColorStop(0.5, '#ffffff')
          grad.addColorStop(1.0, '#00ff00')
          this.context.fillStyle = grad
          this.context.fillRect(0, 30, 100, 100)
        })
    }
    .width('100%')
    .height('100%')
  }
}

en-us_image_0000001239032419

CanvasDirection

Since API version 9, this API is supported in ArkTS widgets.

NameDescription
inheritThe text direction is inherited from the <Canvas> component.
ltrThe text direction is from left to right.
rtlThe text direction is from right to left.

CanvasFillRule

Since API version 9, this API is supported in ArkTS widgets.

NameDescription
evenoddThe inside part of a shape is determined based on whether the counting result is an odd number or not.
nonzeroThe inside part of a shape is determined based on whether the counting result is zero or not.

CanvasLineCap

Since API version 9, this API is supported in ArkTS widgets.

NameDescription
buttThe ends of the line are squared off, and the line does not extend beyond its two endpoints.
roundThe line is extended at the endpoints by a half circle whose diameter is equal to the line width.
squareThe line is extended at the endpoints by a rectangle whose width is equal to half the line width and height equal to the line width.

CanvasLineJoin

Since API version 9, this API is supported in ArkTS widgets.

NameDescription
bevelThe intersection is a triangle. The rectangular corner of each line is independent.
miterThe intersection has a miter corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in miterLimit.
roundThe intersection is a sector, whose radius at the rounded corner is equal to the line width.

CanvasTextAlign

Since API version 9, this API is supported in ArkTS widgets.

NameDescription
centerThe text is center-aligned.
startThe text is aligned with the start bound.
endThe text is aligned with the end bound.
leftThe text is left-aligned.
rightThe text is right-aligned.

CanvasTextBaseline

Since API version 9, this API is supported in ArkTS widgets.

NameDescription
alphabeticThe text baseline is the normal alphabetic baseline.
bottomThe text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.
hangingThe text baseline is a hanging baseline over the text.
ideographicThe text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excessive character.
middleThe text baseline is in the middle of the text bounding box.
topThe text baseline is on the top of the text bounding box.

ImageSmoothingQuality

Since API version 9, this API is supported in ArkTS widgets.

NameDescription
lowLow quality.
mediumMedium quality.
highHigh quality.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙ArkTS-based Declarative Development Paradigm

harmony 鸿蒙@ohos.multimedia.avCastPicker (AVCastPicker)

harmony 鸿蒙Property Animation

harmony 鸿蒙Enums

harmony 鸿蒙Blank

harmony 鸿蒙Button

harmony 鸿蒙CalendarPicker

harmony 鸿蒙Checkbox

harmony 鸿蒙CheckboxGroup

harmony 鸿蒙DataPanel

  • 所属分类: 后端技术
  • 本文标签: 鸿蒙 软件
  • 版权声明: 本文链接 https://seaxiang.com/blog/b513679dbd894f8b901fe73ecfb55bd9