diff --git "a/en/application-dev/reference/arkui-js/arkui-js - \345\277\253\346\215\267\346\226\271\345\274\217.lnk" "b/en/application-dev/reference/arkui-js/arkui-js - \345\277\253\346\215\267\346\226\271\345\274\217.lnk" deleted file mode 100644 index d054f4afc6568d1c27a58eaead0e5c8307bc9f49..0000000000000000000000000000000000000000 Binary files "a/en/application-dev/reference/arkui-js/arkui-js - \345\277\253\346\215\267\346\226\271\345\274\217.lnk" and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md b/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md index e9dc8c57cd6388134b548137b98849640d768e8f..8e7eff04944f47fa1e8aede82e2a06bf7dada901 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md @@ -1,236 +1,82 @@ -# CanvasRenderingContext2D - - -**CanvasRenderingContext2D** allows you to draw rectangles, text, images, and other objects on a canvas. - -- Example - - ``` - -
- - - -
- ``` - - ``` - // xxx.js - export default { - handleClick() { - const el = this.$refs.canvas1; - const ctx = el.getContext('2d'); - ctx.beginPath(); - ctx.arc(100, 75, 50, 0, 6.28); - ctx.stroke(); - }, - antialias() { - const el = this.$refs.canvas1; - const ctx = el.getContext('2d', { antialias: true }); - ctx.beginPath(); - ctx.arc(100, 75, 50, 0, 6.28); - ctx.stroke(); +# CanvasRenderingContext2D + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> Supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. + +**CanvasRenderingContext2D** allows you to draw rectangles, text, images, and other objects on a canvas. + + +- Example + ``` + +
+ + + +
+ ``` + + ``` + // xxx.js + export default { + handleClick() { + const el = this.$refs.canvas1; + const ctx = el.getContext('2d'); + ctx.beginPath(); + ctx.arc(100, 75, 50, 0, 6.28); + ctx.stroke(); + }, + antialias() { + const el = this.$refs.canvas1; + const ctx = el.getContext('2d', { antialias: true }); + ctx.beginPath(); + ctx.arc(100, 75, 50, 0, 6.28); + ctx.stroke(); } } - ``` - - -- Anti-aliasing disabled - - ![](figures/en-us_image_0000001214837333.png) - -- Anti-aliasing enabled - - ![](figures/screenshot-8.png) - - -## Attributes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Description

-

fillStyle

-

<color> | CanvasGradient | CanvasPattern

-

-

-

Style to fill an area.

-
  • When the type is <color>, this parameter indicates the color of the filling area.
  • When the type is CanvasGradient, this parameter indicates a gradient object, which is created using the createLinearGradient() method.
  • When the type is CanvasPattern, use the createPattern() method to create a pattern.
-

lineWidth

-

number

-

-

-

Line width.

-

strokeStyle

-

<color> | CanvasGradient | CanvasPattern

-

-

-

Stroke style.

-
  • When the type is <color>, this parameter indicates the stroke color.
  • When the type is CanvasGradient, this parameter indicates a gradient object, which is created using the createLinearGradient() method.
  • When the type is CanvasPattern, use the createPattern() method to create a pattern.
-

lineCap

-

string

-

butt

-

Style of the specified line endpoint. 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, and each endpoint has added a rectangle whose length is the same as the line thickness and whose width is half of the line thickness.
-

lineJoin

-

string

-

miter

-

Style of the intersection point between line segments. The options are as follows:

-
  • round: The intersection is a sector, whose radius at the rounded corner is equal to the line width.
  • bevel: The intersection is a triangle. The rectangular corner of each line is independent.
  • miter: The 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.
-

miterLimit

-

number

-

10

-

Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.

-

font

-

string

-

"normal normal 14px sans-serif"

-

Font style.

-

Syntax: ctx.font="font-style font-weight font-size font-family"5+

-
  • (Optional) font-style: specifies the font style. Available values are normal and italic.
  • (Optional) font-weight: specifies the font weight. Available values are as follows: normal, bold, bolder, lighter, 100, 200, 300, 400, 500, 600, 700, 800, 900
  • (Optional) font-size: specifies the font size and its row height. The unit can only be pixels.
  • (Optional) font-family: specifies the font family. Available values are sans-serif, serif, and monospace.
-

textAlign

-

string

-

left

-

Text 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.
-
NOTE:

In the ltr layout mode, the value start equals left. In the rtl layout mode, the value start equals right.

-
-

textBaseline

-

string

-

alphabetic

-

Horizontal 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 excessive 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.
-

globalAlpha

-

number

-

-

-

Opacity. 0.0: completely transparent; 1.0: completely opaque.

-

lineDashOffset

-

number

-

0.0

-

Offset of the dashed line. The precision is float.

-

globalCompositeOperation

-

string

-

source-over

-

Composition 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. For details, see Types.

-

shadowBlur

-

number

-

0.0

-

Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.

-

shadowColor

-

<color>

-

-

-

Shadow color.

-

shadowOffsetX

-

number

-

-

-

X-axis shadow offset relative to the original object.

-

shadowOffsetY

-

number

-

-

-

Y-axis shadow offset relative to the original object.

-

imageSmoothingEnabled6+

-

boolean

-

true

-

Whether to adjust the image smoothness during image drawing. The value true indicates that the feature is enabled, and the value false indicates that the feature is disabled.

-
- -### fillStyle + ``` -``` +- Anti-aliasing disabled + + ![en-us_image_0000001214837333](figures/en-us_image_0000001214837333.png) + +- Anti-aliasing enabled + + ![screenshot-8](figures/screenshot-8.png) + + +## Attributes + +| Name | Type | Default Value | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------- | ------------------------------------------------------------ | +| [fillStyle](#fillstyle) | \ \| [CanvasGradient](../arkui-js/js-components-canvas-canvasgradient.md) \| CanvasPattern | - | Style to fill an area.
- When the type is **<color>**, this parameter indicates the color of the filling area.
- When the type is **CanvasGradient**, this parameter indicates a gradient object, which is created using the **createLinearGradient()** method.
- When the type is **CanvasPattern**, this parameter indicates a canvas pattern, which is created using the **createPattern()** method. | +| [lineWidth](#linewidth) | number | - | Line width. | +| [strokeStyle](#strokestyle) | \ \| [CanvasGradient](../arkui-js/js-components-canvas-canvasgradient.md) \| CanvasPattern | - | Stroke style.
- When the type is **<color>**, this parameter indicates the stroke color.
- When the type is **CanvasGradient**, this parameter indicates a gradient object, which is created using the **createLinearGradient()** method.
- When the type is **CanvasPattern**, this parameter indicates a canvas pattern, which is created using the **createPattern()** method. | +| [lineCap](#linecap) | string | butt | Style of the specified line endpoint. 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, and each endpoint has added a rectangle whose length is the same as the line thickness and whose width is half of the line thickness. | +| [lineJoin](#linejoin) | string | miter | Style of the intersection point between line segments. The options are as follows:
- **round**: The intersection is a sector, whose radius at the rounded corner is equal to the line width.
- **bevel**: The intersection is a triangle. The rectangular corner of each line is independent.
- **miter**: The 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**. | +| [miterLimit](#miterlimit) | number | 10 | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet. | +| [font](#font) | string | "normal normal 14px sans-serif" | Font style.
Syntax: ctx.font="font-style font-weight font-size font-family"5+
- (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 row height. The unit can only be pixels.
- (Optional) **font-family**: font family. Available values are **sans-serif**, **serif**, and **monospace**. | +| [textAlign](#textalign) | string | left | Text 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.
>![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> In the **ltr** layout mode, the value **start** equals **left**. In the **rtl** layout mode, the value **start** equals **right**. | +| [textBaseline](#textbaseline) | string | alphabetic | Horizontal 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 excessive 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. | +| [globalAlpha](#globalalpha) | number | - | Opacity.
**0.0**: completely transparent.
**1.0**: completely opaque. | +| [lineDashOffset](#linedashoffset) | number | 0.0 | Offset of the dashed line. The precision is float. | +| [globalCompositeOperation](#globalcompositeoperation) | string | source-over | Composition 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. For details, see [Operation types](#globalcompositeoperation). | +| [shadowBlur](#shadowblur) | number | 0.0 | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float. | +| [shadowColor](#shadowcolor) | <color> | - | Shadow color. | +| [shadowOffsetX](#shadowoffsetx) | number | - | X-axis shadow offset relative to the original object. | +| [shadowOffsetY](#shadowoffsety) | number | - | Y-axis shadow offset relative to the original object. | +| [imageSmoothingEnabled](#imagesmoothingenabled6)6+ | boolean | true | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite. | + + +### fillStyle + + ``` +
-``` + ``` ``` //xxx.js @@ -244,9 +90,10 @@ export default { } ``` -![](figures/en-us_image_0000001166962736.png) +![en-us_image_0000001166962736](figures/en-us_image_0000001166962736.png) + -### lineWidth +### lineWidth ``` @@ -265,11 +112,13 @@ export default { ctx.strokeRect(25, 25, 85, 105); } } + ``` -![](figures/en-us_image_0000001166484430.png) +![en-us_image_0000001166484430](figures/en-us_image_0000001166484430.png) + -### strokeStyle +### strokeStyle ``` @@ -291,9 +140,10 @@ export default { } ``` -![](figures/en-us_image_0000001212124299.png) -### lineCap +![en-us_image_0000001212124299](figures/en-us_image_0000001212124299.png) + +### lineCap ``` @@ -318,9 +168,9 @@ export default { } ``` -![](figures/en-us_image_0000001214837127.png) +![en-us_image_0000001214837127](figures/en-us_image_0000001214837127.png) -### lineJoin +### lineJoin ``` @@ -346,9 +196,9 @@ export default { } ``` -![](figures/en-us_image_0000001214717247.png) +![en-us_image_0000001214717247](figures/en-us_image_0000001214717247.png) -### miterLimit +### miterLimit ``` @@ -374,9 +224,10 @@ export default { } ``` -![](figures/en-us_image_0000001167001464.png) +![en-us_image_0000001167001464](figures/en-us_image_0000001167001464.png) + -### font +### font ``` @@ -397,9 +248,10 @@ export default { } ``` -![](figures/en-us_image_0000001167046832.png) +![en-us_image_0000001167046832](figures/en-us_image_0000001167046832.png) -### textAlign + +### textAlign ``` @@ -418,27 +270,27 @@ export default { ctx.moveTo(140, 10); ctx.lineTo(140, 160); ctx.stroke(); - - ctx.font = '18px sans-serif'; - -// Show the textAlign values. - ctx.textAlign = 'start'; - ctx.fillText('textAlign=start', 140, 60); - ctx.textAlign = 'end'; - ctx.fillText('textAlign=end', 140, 80); - ctx.textAlign = 'left'; + ctx.font = '18px sans-serif'; + // Show the different textAlign values + ctx.textAlign = 'start'; + ctx.fillText('textAlign=start', 140, 60); + ctx.textAlign = 'end'; + ctx.fillText('textAlign=end', 140, 80); + ctx.textAlign = 'left'; ctx.fillText('textAlign=left', 140, 100); - ctx.textAlign = 'center'; - ctx.fillText('textAlign=center',140, 120); - ctx.textAlign = 'right'; + ctx.textAlign = 'center'; + ctx.fillText('textAlign=center',140, 120); + ctx.textAlign = 'right'; ctx.fillText('textAlign=right',140, 140); } } + ``` -![](figures/en-us_image_0000001167472798.png) -### textBaseline +![en-us_image_0000001167472798](figures/en-us_image_0000001167472798.png) + +### textBaseline ``` @@ -457,9 +309,7 @@ export default { ctx.moveTo(0, 120); ctx.lineTo(400, 120); ctx.stroke(); - ctx.font = '20px sans-serif'; - ctx.textBaseline = 'top'; ctx.fillText('Top', 10, 120); ctx.textBaseline = 'bottom'; @@ -474,9 +324,9 @@ export default { } ``` -![](figures/en-us_image_0000001169315920.png) +![en-us_image_0000001169315920](figures/en-us_image_0000001169315920.png) -### globalAlpha +### globalAlpha ``` @@ -496,14 +346,14 @@ export default { ctx.globalAlpha = 0.4; ctx.fillStyle = 'rgb(0,0,255)'; ctx.fillRect(50, 50, 50, 50); - + } } ``` -![](figures/en-us_image_0000001167953648.png) +![en-us_image_0000001167953648](figures/en-us_image_0000001167953648.png) -### lineDashOffset +### lineDashOffset ``` @@ -526,121 +376,66 @@ export default { } ``` -![](figures/en-us_image_0000001167950468.png) - -### globalCompositeOperation - -- Enumerates the operation types. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Value

-

Description

-

source-over

-

Displays the new drawing above the existing drawing. This attribute is used by default.

-

source-atop

-

Displays the new drawing on the top of the existing drawing.

-

source-in

-

Displays the new drawing inside the existing drawing.

-

source-out

-

Displays part of the new drawing that is outside of the existing drawing.

-

destination-over

-

Displays the existing drawing above the new drawing.

-

destination-atop

-

Displays the existing drawing above the new drawing.

-

destination-in

-

Displays the existing drawing inside the new drawing.

-

destination-out

-

Displays part of the existing drawing that is outside of the new drawing.

-

lighter

-

Displays both the new drawing and the existing drawing.

-

copy

-

Displays the new drawing and neglects the existing drawing.

-

xor

-

Combines the new drawing and existing drawing using the XOR operation.

-
- - -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.fillStyle = 'rgb(255,0,0)'; - ctx.fillRect(20, 20, 50, 50); - ctx.globalCompositeOperation = 'source-over'; - ctx.fillStyle = 'rgb(0,0,255)'; - ctx.fillRect(50, 50, 50, 50); - // Start drawing second example - ctx.fillStyle = 'rgb(255,0,0)'; - ctx.fillRect(120, 20, 50, 50); - ctx.globalCompositeOperation = 'destination-over'; - ctx.fillStyle = 'rgb(0,0,255)'; - ctx.fillRect(150, 50, 50, 50); - } +![en-us_image_0000001167950468](figures/en-us_image_0000001167950468.png) + +### globalCompositeOperation + +- Operation types + | Value | Description | + | ---------------- | ------------------------ | + | source-over | Displays the new drawing above the existing drawing. This attribute is used by default. | + | source-atop | Displays the new drawing on the top of the existing drawing. | + | source-in | Displays the new drawing inside the existing drawing. | + | source-out | Displays part of the new drawing that is outside of the existing drawing. | + | destination-over | Displays the existing drawing above the new drawing. | + | destination-atop | Displays the existing drawing on the top of the new drawing. | + | destination-in | Displays the existing drawing inside the new drawing. | + | destination-out | Displays part of the existing drawing that is outside of the new drawing. | + | lighter | Displays both the new drawing and the existing drawing. | + | copy | Displays the new drawing and neglects the existing drawing. | + | xor | Combines the new drawing and existing drawing using the XOR operation.| + +- Example +``` + +
+ +
+``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.fillStyle = 'rgb(255,0,0)'; + ctx.fillRect(20, 20, 50, 50); + ctx.globalCompositeOperation = 'source-over'; + ctx.fillStyle = 'rgb(0,0,255)'; + ctx.fillRect(50, 50, 50, 50); + // Start drawing second example + ctx.fillStyle = 'rgb(255,0,0)'; + ctx.fillRect(120, 20, 50, 50); + ctx.globalCompositeOperation = 'destination-over'; + ctx.fillStyle = 'rgb(0,0,255)'; + ctx.fillRect(150, 50, 50, 50); } - ``` - - ![](figures/en-us_image_0000001213192781.png) + } + ``` - In the above example, the blue rectangle represents the new drawing, and the red rectangle represents the existing drawing. + ![en-us_image_0000001213192781](figures/en-us_image_0000001213192781.png) + In the above example, the blue rectangle represents the new drawing, and the red rectangle represents the existing drawing. -### shadowBlur +### shadowBlur -``` + ```
-``` + ``` ``` //xxx.js @@ -656,9 +451,9 @@ export default { } ``` -![](figures/en-us_image_0000001168111514.png) +![en-us_image_0000001168111514](figures/en-us_image_0000001168111514.png) -### shadowColor +### shadowColor ``` @@ -681,9 +476,9 @@ export default { } ``` -![](figures/en-us_image_0000001168111610.png) +![en-us_image_0000001168111610](figures/en-us_image_0000001168111610.png) -### shadowOffsetX +### shadowOffsetX ``` @@ -707,9 +502,10 @@ export default { } ``` -![](figures/en-us_image_0000001167631876.png) -### shadowOffsetY +![en-us_image_0000001167631876](figures/en-us_image_0000001167631876.png) + +### shadowOffsetY ``` @@ -733,9 +529,9 @@ export default { } ``` -![](figures/en-us_image_0000001213193285.png) +![en-us_image_0000001213193285](figures/en-us_image_0000001213193285.png) -### imageSmoothingEnabled6+ +### imageSmoothingEnabled6+ ``` @@ -760,2498 +556,1384 @@ export default { } ``` -![](figures/smoothoff.png) +![smoothoff](figures/smoothoff.png) + + + +## Methods -## Methods -### fillRect +### fillRect -fillRect\(x: number, y: number, width:number, height: number\): void +fillRect(x: number, y: number, width:number, height: number): void Fills a rectangle on the canvas. -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

x

-

number

-

X-coordinate of the upper left corner of the rectangle

-

y

-

number

-

Y-coordinate of the upper left corner of the rectangle

-

width

-

number

-

Width of the rectangle.

-

height

-

number

-

Height of the rectangle.

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.fillRect(20, 20, 200, 150); - } +- Parameters + | Name | Type | Description | + | ------ | ------ | ------------- | + | x | number | X-coordinate of the upper left corner of the rectangle.| + | y | number | Y-coordinate of the upper left corner of the rectangle.| + | width | number | Width of the rectangle. | + | height | number | Height of the rectangle. | + +- Example +``` + +
+ +
+``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.fillRect(20, 20, 200, 150); } - ``` - - ![](figures/en-us_image_0000001214811029.png) + } + ``` + ![en-us_image_0000001214811029](figures/en-us_image_0000001214811029.png) -### clearRect +### clearRect -clearRect\(x: number, y: number, width:number, height: number\): void +clearRect(x: number, y: number, width:number, height: number): void Clears the content in a rectangle on the canvas. -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

x

-

number

-

X-coordinate of the upper left corner of the rectangle

-

y

-

number

-

Y-coordinate of the upper left corner of the rectangle

-

width

-

number

-

Width of the rectangle.

-

height

-

number

-

Height of the rectangle.

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.fillStyle = 'rgb(0,0,255)'; - ctx.fillRect(0, 0, 400, 200); - ctx.clearRect(20, 20, 150, 100); - } +- Parameters + | Name | Type | Description | + | ------ | ------ | ------------- | + | x | number | X-coordinate of the upper left corner of the rectangle.| + | y | number | Y-coordinate of the upper left corner of the rectangle.| + | width | number | Width of the rectangle. | + | height | number | Height of the rectangle. | + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.fillStyle = 'rgb(0,0,255)'; + ctx.fillRect(0, 0, 400, 200); + ctx.clearRect(20, 20, 150, 100); } - ``` + } + ``` - ![](figures/en-us_image_0000001214619417.png) + ![en-us_image_0000001214619417](figures/en-us_image_0000001214619417.png) -### strokeRect +### strokeRect -strokeRect\(x: number, y: number, width:number, height: number\): void +strokeRect(x: number, y: number, width:number, height: number): void Draws a rectangle stroke on the canvas. -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

x

-

number

-

X-coordinate of the upper left corner of the rectangle stroke

-

y

-

number

-

Y-coordinate of the upper left corner of the rectangle stroke

-

width

-

number

-

Width of the rectangle.

-

height

-

number

-

Height of the rectangle.

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.strokeRect(30, 30, 200, 150); - } +- Parameters + | Name | Type | Description | + | ------ | ------ | ------------ | + | x | number | X-coordinate of the upper left corner of the rectangle stroke.| + | y | number | Y-coordinate of the upper left corner of the rectangle stroke.| + | width | number | Width of the rectangle. | + | height | number | Height of the rectangle. | + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.strokeRect(30, 30, 200, 150); } - ``` + } + ``` - ![](figures/en-us_image_0000001214822091.png) + ![en-us_image_0000001214822091](figures/en-us_image_0000001214822091.png) -### fillText +### fillText -fillText\(text: string, x: number, y: number\): void +fillText(text: string, x: number, y: number): void Draws filled text on the canvas. -- Parameters - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

text

-

string

-

Text to draw

-

x

-

number

-

X-coordinate of the lower left corner of the text

-

y

-

number

-

Y-coordinate of the lower left corner of the text stroke

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.font = '35px sans-serif'; - ctx.fillText("Hello World!", 10, 60); - } +- Parameters + | Name | Type | Description | + | ---- | ------ | --------------- | + | text | string | Text to draw. | + | x | number | X-coordinate of the lower left corner of the text.| + | y | number | Y-coordinate of the lower left corner of the text.| + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.font = '35px sans-serif'; + ctx.fillText("Hello World!", 10, 60); } - ``` - - ![](figures/en-us_image_0000001214469787.png) + } + ``` + ![en-us_image_0000001214469787](figures/en-us_image_0000001214469787.png) -### strokeText +### strokeText -strokeText\(text: string, x: number, y: number\): void +strokeText(text: string, x: number, y: number): void Draws a text stroke on the canvas. -- Parameters - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

text

-

string

-

Text to draw

-

x

-

number

-

X-coordinate of the lower left corner of the text

-

y

-

number

-

Y-coordinate of the lower left corner of the text

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.font = '25px sans-serif'; - ctx.strokeText("Hello World!", 10, 60); - } +- Parameters + | Name | Type | Description | + | ---- | ------ | --------------- | + | text | string | Text to draw. | + | x | number | X-coordinate of the lower left corner of the text.| + | y | number | Y-coordinate of the lower left corner of the text.| + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.font = '25px sans-serif'; + ctx.strokeText("Hello World!", 10, 60); } - ``` - - ![](figures/en-us_image_0000001214460669.png) - - -### measureText - -measureText\(text: string\): TextMetrics - -Returns a **TextMetrics** object used to obtain the width of specified text. - -- Parameters - - - - - - - - - - - - -

Name

-

Type

-

Description

-

text

-

string

-

Text to be measured

-
- -- Return Value - - - - - - - - - - -

Type

-

Description

-

TextMetrics

-

Object that contains the text width. You can obtain the width by TextMetrics.width.

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.font = '20px sans-serif'; - var txt = 'Hello World'; - ctx.fillText("width:" + ctx.measureText(txt).width, 20, 60); - ctx.fillText(txt, 20, 110); - } + } + ``` + + ![en-us_image_0000001214460669](figures/en-us_image_0000001214460669.png) + +### measureText + +measureText(text: string): TextMetrics + +Returns a **TextMetrics** object used to obtain the width of specified text. + +- Parameters + | Name | Type | Description | + | ---- | ------ | ---------- | + | text | string | Text to be measured.| + +- Return value + | Type | Description | + | ----------- | -------------------------------------- | + | TextMetrics | Object that contains the text width. You can obtain the width by **TextMetrics.width**.| + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.font = '20px sans-serif'; + var txt = 'Hello World'; + ctx.fillText("width:" + ctx.measureText(txt).width, 20, 60); + ctx.fillText(txt, 20, 110); } - ``` - - ![](figures/en-us_image_0000001169142476.png) + } + ``` + ![en-us_image_0000001169142476](figures/en-us_image_0000001169142476.png) -### stroke -stroke\(\): void +### stroke +stroke(): void Draws a stroke. -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.moveTo(25, 25); - ctx.lineTo(25, 250); - ctx.lineWidth = '6'; - ctx.strokeStyle = 'rgb(0,0,255)'; - ctx.stroke(); - } +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.moveTo(25, 25); + ctx.lineTo(25, 250); + ctx.lineWidth = '6'; + ctx.strokeStyle = 'rgb(0,0,255)'; + ctx.stroke(); } - ``` - - ![](figures/en-us_image_0000001236697937.png) + } + ``` + ![en-us_image_0000001236697937](figures/en-us_image_0000001236697937.png) -### beginPath -beginPath\(\): void +### beginPath +beginPath(): void Creates a drawing path. -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.beginPath(); - ctx.lineWidth = '6'; - ctx.strokeStyle = '#0000ff'; - ctx.moveTo(15, 80); - ctx.lineTo(280, 80); - ctx.stroke(); - } +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.beginPath(); + ctx.lineWidth = '6'; + ctx.strokeStyle = '#0000ff'; + ctx.moveTo(15, 80); + ctx.lineTo(280, 80); + ctx.stroke(); } - ``` - - ![](figures/en-us_image_0000001214629745.png) + } + ``` + ![en-us_image_0000001214629745](figures/en-us_image_0000001214629745.png) -### moveTo -moveTo\(x: number, y: number\): void +### moveTo +moveTo(x: number, y: number): void Moves a drawing path to a target position on the canvas. -- Parameters - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

x

-

number

-

X-coordinate of the target position

-

y

-

number

-

Y-coordinate of the target position.

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.beginPath(); - ctx.moveTo(10, 10); - ctx.lineTo(280, 160); - ctx.stroke(); - } +- Parameters + | Name | Type | Description | + | ---- | ------ | --------- | + | x | number | X-coordinate of the target position.| + | y | number | Y-coordinate of the target position.| + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.beginPath(); + ctx.moveTo(10, 10); + ctx.lineTo(280, 160); + ctx.stroke(); } - ``` - - ![](figures/en-us_image_0000001169309948.png) + } + ``` + ![en-us_image_0000001169309948](figures/en-us_image_0000001169309948.png) -### lineTo -lineTo\(x: number, y: number\): void +### lineTo +lineTo(x: number, y: number): void Connects the current point to a target position using a straight line. -- Parameters - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

x

-

number

-

X-coordinate of the target position

-

y

-

number

-

Y-coordinate of the target position.

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.beginPath(); - ctx.moveTo(10, 10); - ctx.lineTo(280, 160); - ctx.stroke(); - } +- Parameters + | Name | Type | Description | + | ---- | ------ | --------- | + | x | number | X-coordinate of the target position.| + | y | number | Y-coordinate of the target position.| + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.beginPath(); + ctx.moveTo(10, 10); + ctx.lineTo(280, 160); + ctx.stroke(); } - ``` - - ![](figures/en-us_image_0000001169469914.png) + } + ``` + ![en-us_image_0000001169469914](figures/en-us_image_0000001169469914.png) -### closePath -closePath\(\): void +### closePath +closePath(): void Draws a closed path. -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.beginPath(); - ctx.moveTo(30, 30); - ctx.lineTo(110, 30); - ctx.lineTo(70, 90); - ctx.closePath(); - ctx.stroke(); - } +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.beginPath(); + ctx.moveTo(30, 30); + ctx.lineTo(110, 30); + ctx.lineTo(70, 90); + ctx.closePath(); + ctx.stroke(); } - ``` - - ![](figures/en-us_image_0000001169151508.png) + } + ``` + ![en-us_image_0000001169151508](figures/en-us_image_0000001169151508.png) -### createPattern +### createPattern -createPattern\(image: Image, repetition: string\): Object +createPattern(image: Image, repetition: string): Object Creates a pattern for image filling based on a specified source image and repetition mode. -- Parameters - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

image

-

Image

-

Source image. For details, see Image.

-

repetition

-

string

-

Repetition mode. The value can be "repeat", "repeat-x", "repeat-y", or "no-repeat".

-
- -- Return Value - - - - - - - - - - -

Type

-

Description

-

Object

-

Pattern of image filling.

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - var img = new Image(); - img.src = 'common/images/example.jpg'; - var pat = ctx.createPattern(img, 'repeat'); - ctx.fillStyle = pat; - ctx.fillRect(0, 0, 20, 20); - } +- Parameters + | Name | Type | Description | + | ---------- | ------ | ---------------------------------------- | + | image | Image | Source image. For details, see [Image](../arkui-js/js-components-canvas-image.md).| + | repetition | string | Repetition mode. The value can be **"repeat"**, **"repeat-x"**, **"repeat-y"**, or **"no-repeat"**.| + +- Return value + | Type | Description | + | ------ | ----------------- | + | Object | Pattern of image filling.| + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + var img = new Image(); + img.src = 'common/images/example.jpg'; + var pat = ctx.createPattern(img, 'repeat'); + ctx.fillStyle = pat; + ctx.fillRect(0, 0, 20, 20); } - ``` - - ![](figures/en-us_image_0000001169301188.png) + } + ``` + ![en-us_image_0000001169301188](figures/en-us_image_0000001169301188.png) -### bezierCurveTo +### bezierCurveTo -bezierCurveTo\(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number\): void +bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void Draws a cubic bezier curve on the canvas. -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

cp1x

-

number

-

X-coordinate of the first parameter of the bezier curve

-

cp1y

-

number

-

Y-coordinate of the first parameter of the bezier curve

-

cp2x

-

number

-

X-coordinate of the second parameter of the bezier curve

-

cp2y

-

number

-

Y-coordinate of the second parameter of the bezier curve

-

x

-

number

-

X-coordinate of the end point on the bezier curve

-

y

-

number

-

Y-coordinate of the end point on the bezier curve

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.beginPath(); - ctx.moveTo(10, 10); - ctx.bezierCurveTo(20, 100, 200, 100, 200, 20); - ctx.stroke(); - } +- Parameters + | Name | Type | Description | + | ---- | ------ | -------------- | + | cp1x | number | X-coordinate of the first parameter of the bezier curve.| + | cp1y | number | Y-coordinate of the first parameter of the bezier curve.| + | cp2x | number | X-coordinate of the second parameter of the bezier curve.| + | cp2y | number | Y-coordinate of the second parameter of the bezier curve.| + | x | number | X-coordinate of the end point on the bezier curve. | + | y | number | Y-coordinate of the end point on the bezier curve. | + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.beginPath(); + ctx.moveTo(10, 10); + ctx.bezierCurveTo(20, 100, 200, 100, 200, 20); + ctx.stroke(); } - ``` - - ![](figures/en-us_image_0000001214621177.png) + } + ``` + ![en-us_image_0000001214621177](figures/en-us_image_0000001214621177.png) -### quadraticCurveTo +### quadraticCurveTo -quadraticCurveTo\(cpx: number, cpy: number, x: number, y: number\): void +quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void Draws a quadratic curve on the canvas. -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

cpx

-

number

-

X-coordinate of the bezier curve parameter

-

cpy

-

number

-

Y-coordinate of the bezier curve parameter

-

x

-

number

-

X-coordinate of the end point on the bezier curve

-

y

-

number

-

Y-coordinate of the end point on the bezier curve

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.beginPath(); - ctx.moveTo(20, 20); - ctx.quadraticCurveTo(100, 100, 200, 20); - ctx.stroke(); - } +- Parameters + | Name | Type | Description | + | ---- | ------ | ----------- | + | cpx | number | X-coordinate of the bezier curve parameter.| + | cpy | number | Y-coordinate of the bezier curve parameter.| + | x | number | X-coordinate of the end point on the bezier curve.| + | y | number | Y-coordinate of the end point on the bezier curve.| + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.beginPath(); + ctx.moveTo(20, 20); + ctx.quadraticCurveTo(100, 100, 200, 20); + ctx.stroke(); } - ``` - - ![](figures/en-us_image_0000001169461910.png) + } + ``` + ![en-us_image_0000001169461910](figures/en-us_image_0000001169461910.png) -### arc -arc\(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise: boolean\): void +### arc +arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise: boolean): void Draws an arc on the canvas. -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

x

-

number

-

X-coordinate of the center point of the arc

-

y

-

number

-

Y-coordinate of the center point of the arc

-

radius

-

number

-

Radius of the arc

-

startAngle

-

number

-

Start radian of the arc

-

endAngle

-

number

-

End radian of the arc

-

anticlockwise

-

boolean

-

Whether to draw the arc counterclockwise

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.beginPath(); - ctx.arc(100, 75, 50, 0, 6.28); - ctx.stroke(); - } +- Parameters + | Name | Type | Description | + | ------------- | ------- | ---------- | + | x | number | X-coordinate of the center point of the arc.| + | y | number | Y-coordinate of the center point of the arc.| + | radius | number | Radius of the arc. | + | startAngle | number | Start radian of the arc. | + | endAngle | number | End radian of the arc. | + | anticlockwise | boolean | Whether to draw the arc counterclockwise.| + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.beginPath(); + ctx.arc(100, 75, 50, 0, 6.28); + ctx.stroke(); } - ``` - - ![](figures/en-us_image_0000001169470288.png) + } + ``` + ![en-us_image_0000001169470288](figures/en-us_image_0000001169470288.png) -### arcTo +### arcTo -arcTo\(x1: number, y1: number, x2: number, y2: number, radius: number\): void +arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void Draws an arc based on the radius and points on the arc. -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

x1

-

number

-

X-coordinate of the first point on the arc

-

y1

-

number

-

Y-coordinate of the first point on the arc

-

x2

-

number

-

X-coordinate of the second point on the arc

-

y2

-

number

-

Y-coordinate of the second point on the arc

-

radius

-

number

-

Radius of the arc

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.moveTo(100, 20); - ctx.arcTo(150, 20, 150, 70, 50); // Create an arc. - ctx.stroke(); - } +- Parameters + | Name | Type | Description | + | ------ | ------ | --------------- | + | x1 | number | X-coordinate of the first point on the arc.| + | y1 | number | Y-coordinate of the first point on the arc.| + | x2 | number | X-coordinate of the second point on the arc.| + | y2 | number | Y-coordinate of the second point on the arc.| + | radius | number | Radius of the arc. | + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.moveTo(100, 20); + ctx.arcTo(150, 20, 150, 70, 50); // Create an arc. + ctx.stroke(); } - ``` - - ![](figures/en-us_image_0000001169143586.png) - - -### ellipse6+ - -ellipse\(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise: number\): void - -Draws an ellipse in the specified rectangular region. - -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

x

-

number

-

X-coordinate of the ellipse center

-

y

-

number

-

Y-coordinate of the ellipse center

-

radiusX

-

number

-

Ellipse radius on the x-axis.

-

radiusY

-

number

-

Ellipse radius on the y-axis.

-

rotation

-

number

-

Rotation angle of the ellipse. The unit is radian.

-

startAngle

-

number

-

Angle of the start point for drawing the ellipse. The unit is radian.

-

endAngle

-

number

-

Angle of the end point for drawing the ellipse. The angle is represented by radians.

-

anticlockwise

-

number

-

Whether to draw the ellipse in the anticlockwise direction. The value 0 indicates clockwise and the value 1 indicates anticlockwise. This parameter is optional. The default value is 0.

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.beginPath(); - ctx.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI, 1); - ctx.stroke(); - } + } + ``` + + ![en-us_image_0000001169143586](figures/en-us_image_0000001169143586.png) + +### ellipse6+ + +ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise: number): void + +Draws an ellipse in the specified rectangular region on the canvas. + +- Parameters + | Name | Type | Description | + | ------------- | ------ | ------------------------------------ | + | x | number | X-coordinate of the ellipse center. | + | y | number | Y-coordinate of the ellipse center. | + | radiusX | number | Ellipse radius on the x-axis. | + | radiusY | number | Ellipse radius on the y-axis. | + | rotation | number | Rotation angle of the ellipse. The unit is radian. | + | startAngle | number | Angle of the start point for drawing the ellipse. The unit is radian. | + | endAngle | number | Angle of the end point for drawing the ellipse. The unit is radian. | + | anticlockwise | number | Whether to draw the ellipse counterclockwise. The value **0** means clockwise, and **1** means counterclockwise. This parameter is optional. The default value is **0**.| + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.beginPath(); + ctx.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI, 1); + ctx.stroke(); } - ``` - - ![](figures/ellipse.png) - - -### rect - -rect\(x: number, y: number, width: number, height: number\): void - -Creates a rectangle. - -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

x

-

number

-

X-coordinate of the upper left corner of the rectangle

-

y

-

number

-

Y-coordinate of the upper left corner of the rectangle

-

width

-

number

-

Width of the rectangle.

-

height

-

number

-

Height of the rectangle.

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.rect(20, 20, 100, 100); // Create a 100*100 rectangle at (20, 20) - ctx.stroke(); // Draw it - } + } + ``` + + ![ellipse](figures/ellipse.png) + + +### rect +rect(x: number, y: number, width: number, height: number): void + +Creates a rectangle on the canvas. + +- Parameters + | Name | Type | Description | + | ------ | ------ | ------------- | + | x | number | X-coordinate of the upper left corner of the rectangle.| + | y | number | Y-coordinate of the upper left corner of the rectangle.| + | width | number | Width of the rectangle. | + | height | number | Height of the rectangle. | + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.rect(20, 20, 100, 100); // Create a 100*100 rectangle at (20, 20). + ctx.stroke(); // Draw it } - ``` - - ![](figures/en-us_image_0000001214630783.png) - + } + ``` -### fill + ![en-us_image_0000001214630783](figures/en-us_image_0000001214630783.png) -fill\(\): void +### fill -Fills the area inside a closed path. +fill(): void -- Example +Fills the area inside a closed path on the canvas. - ``` - -
- -
- ``` +- Example + ``` + +
+ +
+ ``` - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.rect(20, 20, 100, 100); // Create a 100*100 rectangle at (20, 20). - ctx.fill(); // Fill the rectangle using default settings. - } + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.rect(20, 20, 100, 100); // Create a 100*100 rectangle at (20, 20). + ctx.fill(); // Fill the rectangle using default settings. } - ``` - - ![](figures/en-us_image_0000001214703717.png) + } + ``` + ![en-us_image_0000001214703717](figures/en-us_image_0000001214703717.png) -### clip +### clip -clip\(\): void +clip(): void Sets the current path to a clipping path. -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.rect(0, 0, 200, 200); - ctx.stroke(); - ctx.clip(); - // Clip a rectangle and fill it with red paint. - ctx.fillStyle = "rgb(255,0,0)"; - ctx.fillRect(0, 0, 150, 150); - } +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.rect(0, 0, 200, 200); + ctx.stroke(); + ctx.clip(); + // Clip a rectangle and fill it with red paint. + ctx.fillStyle = "rgb(255,0,0)"; + ctx.fillRect(0, 0, 150, 150); } - ``` - - ![](figures/en-us_image_0000001169303414.png) + } + ``` + ![en-us_image_0000001169303414](figures/en-us_image_0000001169303414.png) -### rotate +### rotate -rotate\(rotate: number\): void +rotate(rotate: number): void Rotates a canvas clockwise around its coordinate axes. -- Parameters - - - - - - - - - - - - -

Name

-

Type

-

Description

-

rotate

-

number

-

Clockwise rotation angle. You can use Math.PI / 180 to convert the angle to a radian.

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.rotate(45 * Math.PI / 180); // Rotate the rectangle 45 degrees. - ctx.fillRect(70, 20, 50, 50); - } +- Parameters + | Name | Type | Description | + | ------ | ------ | ---------------------------------------- | + | rotate | number | Clockwise rotation angle. You can use **Math.PI / 180** to convert the angle to a radian.| + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.rotate(45 * Math.PI / 180); // Rotate the rectangle 45 degrees + ctx.fillRect(70, 20, 50, 50); } - ``` - - ![](figures/en-us_image_0000001169463368.png) - - -### scale - -scale\(x: number, y: number\): void - -Scales a canvas based on scaling factors. - -- Parameters - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

x

-

number

-

Horizontal scale factor.

-

y

-

number

-

Vertical scale factor.

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.strokeRect(10, 10, 25, 25); - ctx.scale(2, 2);// Set a 200% scale factor for the rectangle. - ctx.strokeRect(10, 10, 25, 25); - } + } + ``` + + ![en-us_image_0000001169463368](figures/en-us_image_0000001169463368.png) + +### scale + +scale(x: number, y: number): void + +Scales the canvas based on scale factors. + +- Parameters + | Name | Type | Description | + | ---- | ------ | ----------- | + | x | number | Horizontal scale factor.| + | y | number | Vertical scale factor.| + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.strokeRect(10, 10, 25, 25); + ctx.scale(2, 2);// Scale to 200%. + ctx.strokeRect(10, 10, 25, 25); } - ``` - - ![](figures/en-us_image_0000001214463281.png) + } + ``` + ![en-us_image_0000001214463281](figures/en-us_image_0000001214463281.png) -### transform +### transform -transform\(scaleX: number, skewX: number, skewY: number, scale: number, translateX: number, translateY: number\): void +transform(scaleX: number, skewX: number, skewY: number, scale: number, translateX: number, translateY: 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. ->![](../../public_sys-resources/icon-note.gif) **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 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

scaleX

-

number

-

X-axis scale

-

skewX

-

number

-

X-axis skew

-

skewY

-

number

-

Y-axis skew

-

scaleY

-

number

-

Y-axis scale

-

translateX

-

number

-

X-axis translation

-

translateY

-

number

-

Y-axis translation.

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.fillStyle = 'rgb(0,0,0)'; - ctx.fillRect(0, 0, 100, 100) - ctx.transform(1, 0.5, -0.5, 1, 10, 10); - ctx.fillStyle = 'rgb(255,0,0)'; - ctx.fillRect(0, 0, 100, 100); - ctx.transform(1, 0.5, -0.5, 1, 10, 10); - ctx.fillStyle = 'rgb(0,0,255)'; - ctx.fillRect(0, 0, 100, 100); - } +> ![icon-note.gif](public_sys-resources/icon-note.gif) **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 + | Name | Type | Description | + | ---------- | ------ | -------- | + | scaleX | number | X-axis scale.| + | skewX | number | X-axis skew.| + | skewY | number | Y-axis skew.| + | scaleY | number | Y-axis scale.| + | translateX | number | X-axis translation.| + | translateY | number | Y-axis translation.| + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.fillStyle = 'rgb(0,0,0)'; + ctx.fillRect(0, 0, 100, 100) + ctx.transform(1, 0.5, -0.5, 1, 10, 10); + ctx.fillStyle = 'rgb(255,0,0)'; + ctx.fillRect(0, 0, 100, 100); + ctx.transform(1, 0.5, -0.5, 1, 10, 10); + ctx.fillStyle = 'rgb(0,0,255)'; + ctx.fillRect(0, 0, 100, 100); } - ``` - - ![](figures/en-us_image_0000001214623227.png) - - -### setTransform - -setTransform\(scaleX: number, skewX: number, skewY: number, scale: number, translateX: number, translateY: number\): void - -Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform\(\)** function. - -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

scaleX

-

number

-

X-axis scale

-

skewX

-

number

-

X-axis skew

-

skewY

-

number

-

Y-axis skew

-

scaleY

-

number

-

Y-axis scale

-

translateX

-

number

-

X-axis translation

-

translateY

-

number

-

Y-axis translation.

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.fillStyle = 'rgb(255,0,0)'; - ctx.fillRect(0, 0, 100, 100) - ctx.setTransform(1,0.5, -0.5, 1, 10, 10); - ctx.fillStyle = 'rgb(0,0,255)'; - ctx.fillRect(0, 0, 100, 100); - } + } + ``` + + ![en-us_image_0000001214623227](figures/en-us_image_0000001214623227.png) + +### setTransform + +setTransform(scaleX: number, skewX: number, skewY: number, scale: number, translateX: number, translateY: number): void + +Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** function. + +- Parameters + | Name | Type | Description | + | ---------- | ------ | -------- | + | scaleX | number | X-axis scale.| + | skewX | number | X-axis skew.| + | skewY | number | Y-axis skew.| + | scaleY | number | Y-axis scale.| + | translateX | number | X-axis translation.| + | translateY | number | Y-axis translation.| + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.fillStyle = 'rgb(255,0,0)'; + ctx.fillRect(0, 0, 100, 100) + ctx.setTransform(1,0.5, -0.5, 1, 10, 10); + ctx.fillStyle = 'rgb(0,0,255)'; + ctx.fillRect(0, 0, 100, 100); } - ``` - - ![](figures/en-us_image_0000001168984880.png) + } + ``` + ![en-us_image_0000001168984880](figures/en-us_image_0000001168984880.png) -### translate +### translate -translate\(x: number, y: number\): void +translate(x: number, y: number): void Moves the origin of the coordinate system. -- Parameters - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

x

-

number

-

X-axis translation

-

y

-

number

-

Y-axis translation.

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.fillRect(10, 10, 50, 50); - ctx.translate(70, 70); - ctx.fillRect(10, 10, 50, 50); - } +- Parameters + | Name | Type | Description | + | ---- | ------ | -------- | + | x | number | X-axis translation.| + | y | number | Y-axis translation.| + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.fillRect(10, 10, 50, 50); + ctx.translate(70, 70); + ctx.fillRect(10, 10, 50, 50); } - ``` - - ![](figures/en-us_image_0000001169144864.png) - - -### createPath2D6+ - -createPath2D\(path: Path2D, cmds: string\): Path2D - -Creates a **Path2D** object. - -- Parameters - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

path

-

Path2D

-

Path2D object.

-

cmds

-

string

-

Path description of the SVG image.

-
- -- Return values - - [Path2D object](js-components-canvas-path2d.md) - -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - var path1 = ctx.createPath2D(); - path1.moveTo(100, 100); - path1.lineTo(200, 100); - path1.lineTo(100, 200); - path1.closePath(); - ctx.stroke(path1); - var path2 = ctx.createPath2D("M150 150 L50 250 L250 250 Z"); - ctx.stroke(path2); - var path3 = ctx.createPath2D(path2); - ctx.stroke(path3); - } + } + ``` + + ![en-us_image_0000001169144864](figures/en-us_image_0000001169144864.png) + +### createPath2D6+ + +createPath2D(path: Path2D, cmds: string): Path2D + +Creates a **Path2D** object. + +- Parameters + | Name | Type | Description | + | ---- | ------ | -------------- | + | path | Path2D | **Path2D** object. | + | cmds | string | Path description of the SVG image.| + +- Return value + [Path2D object](../arkui-js/js-components-canvas-path2d.md) + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + var path1 = ctx.createPath2D(); + path1.moveTo(100, 100); + path1.lineTo(200, 100); + path1.lineTo(100, 200); + path1.closePath(); + ctx.stroke(path1); + var path2 = ctx.createPath2D("M150 150 L50 250 L250 250 Z"); + ctx.stroke(path2); + var path3 = ctx.createPath2D(path2); + ctx.stroke(path3); } - ``` - - ![](figures/en-us_image_0000001214824709.png) - - -### drawImage - -drawImage\(image: Image, sx: number, sy: number, sWidth: number, sHeight: number, dx: number, dy: number, dWidth: number, dHeight: number\):void - -Draws an image. - -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

image

-

Image

-

Image resource. For details, see Image.

-

sx

-

number

-

X-coordinate of the upper left corner of the rectangle used to crop the source image.

-

sy

-

number

-

Y-coordinate of the upper left corner of the rectangle used to crop the source image.

-

sWidth

-

number

-

Target width to crop the source image.

-

sHeight

-

number

-

Target height to crop the source image.

-

dx

-

number

-

X-coordinate of the upper left corner of the drawing area on the canvas.

-

dy

-

number

-

Y-coordinate of the upper left corner of the drawing area on the canvas.

-

dWidth

-

number

-

Width of the drawing area.

-

dHeight

-

number

-

Height of the drawing area.

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - var test = this.$element('drawImage'); - var ctx = test.getContext('2d'); - var img = new Image(); - img.src = 'common/image/test.jpg'; - ctx.drawImage(img, 50, 80, 80, 80); - } + } + ``` + + ![en-us_image_0000001214824709](figures/en-us_image_0000001214824709.png) + +### drawImage + +drawImage(image: Image, sx: number, sy: number, sWidth: number, sHeight: number, dx: number, dy: number, dWidth: number, dHeight: number):void + +Draws an image on the canvas. + +- Parameters + | Name | Type | Description | + | ------- | ------ | ---------------------------------------- | + | image | Image | Source image. For details, see [Image](../arkui-js/js-components-canvas-image.md).| + | sx | number | X-coordinate of the upper left corner of the rectangle used to crop the source image. | + | sy | number | Y-coordinate of the upper left corner of the rectangle used to crop the source image. | + | sWidth | number | Target width to crop the source image. | + | sHeight | number | Target height to crop the source image. | + | dx | number | X-coordinate of the upper left corner of the drawing area on the canvas. | + | dy | number | Y-coordinate of the upper left corner of the drawing area on the canvas. | + | dWidth | number | Width of the drawing area. | + | dHeight | number | Height of the drawing area. | + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + var test = this.$element('drawImage'); + var ctx = test.getContext('2d'); + var img = new Image(); + img.src = 'common/image/test.jpg'; + ctx.drawImage(img, 50, 80, 80, 80); } - ``` - - ![](figures/en-us_image_0000001214704759.png) + } + ``` + ![en-us_image_0000001214704759](figures/en-us_image_0000001214704759.png) -### restore +### restore -restore\(\): void +restore(): void Restores the saved drawing context. -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.restore(); - } +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.restore(); } - ``` - + } + ``` -### save +### save -save\(\): void +save(): void Saves the current drawing context. -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.save(); - } +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.save(); } - ``` - - -### createLinearGradient6+ - -createLinearGradient\(x0: number, y0: number, x1: number, y1: number\): Object - -Creates a linear gradient. A CanvasGradient object is returned. For details, see [CanvasGradient](js-components-canvas-canvasgradient.md). - -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

x0

-

number

-

X-coordinate of the start point.

-

y0

-

number

-

Y-coordinate of the start point.

-

x1

-

number

-

X-coordinate of the end point.

-

y1

-

number

-

Y-coordinate of the end point.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

Object

-

Returns the created CanvasGradient object.

-
- -- Example - - ``` - -
- - -
- ``` - - ``` - // xxx.js - export default { - handleClick() { - const el = this.$refs.canvas; - const ctx = el.getContext('2d'); - // Linear gradient: start(50,0) end(300,100) - var gradient = ctx.createLinearGradient(50,0, 300,100); - // Add three color stops - gradient.addColorStop(0.0, 'red'); - gradient.addColorStop(0.5, 'white'); - gradient.addColorStop(1.0, 'green'); - // Set the fill style and draw a rectangle - ctx.fillStyle = gradient; - ctx.fillRect(0, 0, 500, 500); - } + } + ``` + +### createLinearGradient6+ + +createLinearGradient(x0: number, y0: number, x1: number, y1: number): Object + +Creates a linear gradient and returns a **CanvasGradient** object. For details, see [CanvasGradient](../arkui-js/js-components-canvas-canvasgradient.md). + +- Parameters + | Name | Type | Description | + | ---- | ------ | -------- | + | x0 | number | X-coordinate of the start point.| + | y0 | number | Y-coordinate of the start point.| + | x1 | number | X-coordinate of the end point.| + | y1 | number | Y-coordinate of the end point.| + +- Return value + | Type | Description | + | ------ | ---------------------- | + | Object | Created **CanvasGradient** object.| + +- Example + ``` + +
+ + +
+ ``` + + ``` + // xxx.js + export default { + handleClick() { + const el = this.$refs.canvas; + const ctx = el.getContext('2d'); + // Linear gradient: start(50,0) end(300,100) + var gradient = ctx.createLinearGradient(50,0, 300,100); + // Add three color stops + gradient.addColorStop(0.0, 'red'); + gradient.addColorStop(0.5, 'white'); + gradient.addColorStop(1.0, 'green'); + // Set the fill style and draw a rectangle + ctx.fillStyle = gradient; + ctx.fillRect(0, 0, 500, 500); } - ``` - - ![](figures/en-us_image_0000001169303416.png) - - -### createRadialGradient6+ - -createRadialGradient\(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number\): Object - -Creates a radial gradient and returns a **CanvasGradient** object. - -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

x0

-

number

-

X-coordinate of the start point.

-

y0

-

number

-

Y-coordinate of the center of the start circle.

-

r0

-

number

-

Radius of the start circle, which must be a non-negative finite number.

-

x1

-

number

-

X-coordinate of the center of the end circle.

-

y1

-

number

-

Y-coordinate of the center of the end circle.

-

r1

-

number

-

Radius of the end circle, The value must be non-negative and limited.

-
- -- Return Value - - - - - - - - - - -

Type

-

Description

-

Object

-

Returns the created CanvasGradient object.

-
- -- Example - - ``` - -
- - -
- ``` - - ``` - // xxx.js - export default { - handleClick() { - const el = this.$refs.canvas; - const ctx = el.getContext('2d'); - // Radial gradient: inner circle(200,200,r:50) outer circle(200,200,r:200) - var gradient = ctx.createRadialGradient(200,200,50, 200,200,200); - // Add three color stops - gradient.addColorStop(0.0, 'red'); - gradient.addColorStop(0.5, 'white'); - gradient.addColorStop(1.0, 'green'); - // Set the fill style and draw a rectangle - ctx.fillStyle = gradient; - ctx.fillRect(0, 0, 500, 500); - } + } + ``` + + ![en-us_image_0000001169303416](figures/en-us_image_0000001169303416.png) + +### createRadialGradient6+ + +createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): Object + +Creates a radial gradient and returns a **CanvasGradient** object. + +- Parameters + | Name | Type | Description | + | ---- | ------ | ----------------- | + | x0 | number | X-coordinate of the center of the start circle. | + | y0 | number | Y-coordinate of the center of the start circle. | + | r0 | number | Radius of the start circle, which must be a non-negative finite number.| + | x1 | number | X-coordinate of the center of the end circle. | + | y1 | number | Y-coordinate of the center of the end circle. | + | r1 | number | Radius of the end circle, which must be a non-negative finite number.| + +- Return value + | Type | Description | + | ------ | ---------------------- | + | Object | Created **CanvasGradient** object.| + +- Example + ``` + +
+ + +
+ ``` + + ``` + // xxx.js + export default { + handleClick() { + const el = this.$refs.canvas; + const ctx = el.getContext('2d'); + // Radial gradient: inner circle(200,200,r:50) outer circle(200,200,r:200) + var gradient = ctx.createRadialGradient(200,200,50, 200,200,200); + // Add three color stops + gradient.addColorStop(0.0, 'red'); + gradient.addColorStop(0.5, 'white'); + gradient.addColorStop(1.0, 'green'); + // Set the fill style and draw a rectangle + ctx.fillStyle = gradient; + ctx.fillRect(0, 0, 500, 500); } - ``` - - ![](figures/en-us_image_0000001169463370.png) - - -### createImageData - -createImageData\(width: number, height: number, imageData: Object\): Object - -Creates an **ImageData** object. For details, see [ImageData](js-components-canvas-imagedata.md). - -- Parameters - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

width

-

number

-

Width of the ImageData object

-

height

-

number

-

Height of the ImageData object

-

imagedata

-

Object

-

ImageData object with the same width and height copied from the original ImageData object

-
- -- Return Value - - - - - - - - - - -

Type

-

Description

-

Object

-

Returns the newly created ImageData object.

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - imageData = ctx.createImageData(50, 100); // Create ImageData with 50px width and 100px height - newImageData = ctx.createImageData(imageData); // Create ImageData using the input imageData - } + } + ``` + + ![en-us_image_0000001169463370](figures/en-us_image_0000001169463370.png) + +### createImageData + +createImageData(width: number, height: number, imageData: Object): Object + +Creates an **ImageData** object. For details, see [ImageData](../arkui-js/js-components-canvas-imagedata.md). + +- Parameters + | Name | Type | Description | + | --------- | ------ | ----------------- | + | width | number | Width of the **ImageData** object. | + | height | number | Height of the **ImageData** object. | + | imagedata | Object | **ImageData** object with the same width and height copied from the original **ImageData** object.| + +- Return value + | Type | Description | + | ------ | ----------------- | + | Object | Created **ImageData** object.| + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + var imageData = ctx.createImageData(50, 100); // Create ImageData with 50px width and 100px height + var newImageData = ctx.createImageData(imageData); // Create ImageData using the input imageData } - ``` - - -### getImageData - -getImageData\(sx: number, sy: number, sw: number, sh: number\): Object - -Creates an **ImageData** object with pixels in the specified area on the canvas. - -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

sx

-

number

-

X coordinate of the upper left corner of the output area

-

sy

-

number

-

Y coordinate of the upper left corner of the output area

-

sw

-

number

-

Width of the output area

-

sh

-

number

-

Height of the output area

-
- -- Return Value - - - - - - - - - - -

Type

-

Description

-

Object

-

ImageData object that contains pixels in the specified area on the canvas

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - var test = this.$element('getImageData') - var ctx = test.getContext('2d'); - var imageData = ctx.getImageData(0, 0, 280, 300); - } + } + ``` + +### getImageData + +getImageData(sx: number, sy: number, sw: number, sh: number): Object + +Creates an **ImageData** object with pixels in the specified area on the canvas. + +- Parameters + | Name | Type | Description | + | ---- | ------ | --------------- | + | sx | number | X-coordinate of the upper left corner of the output area.| + | sy | number | Y-coordinate of the upper left corner of the output area.| + | sw | number | Width of the output area. | + | sh | number | Height of the output area. | + +- Return value + | Type | Description | + | ------ | ----------------------- | + | Object | **ImageData** object that contains pixels in the specified area on the canvas.| + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const test = this.$element('getImageData') + const ctx = test.getContext('2d'); + var imageData = ctx.getImageData(0, 0, 280, 300); } - ``` - - -### putImageData - -putImageData\(imageData: Object, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth: number, dirtyHeight: number\): void - -Puts the **ImageData** onto a rectangular area on the canvas. - -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

imagedata

-

Object

-

ImageData object with pixels to put onto the canvas

-

dx

-

number

-

X-axis offset of the rectangular area on the canvas

-

dy

-

number

-

Y-axis offset of the rectangular area on the canvas

-

dirtyX

-

number

-

X-axis offset of the upper left corner of the rectangular area relative to that of the source image

-

dirtyY

-

number

-

Y-axis offset of the upper left corner of the rectangular area relative to that of the source image

-

dirtyWidth

-

number

-

Width of the rectangular area to crop the source image

-

dirtyHeight

-

number

-

Height of the rectangular area to crop the source image.

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - var test = this.$element('getImageData') - var ctx = test.getContext('2d'); - var imgData = ctx.createImageData(100, 100); - for (var i = 0; i < imgData.data.length; i += 4) { - imgData.data[i + 0] = 255; - imgData.data[i + 1] = 0; - imgData.data[i + 2] = 0; - imgData.data[i + 3] = 255; - } - ctx.putImageData(imgData, 10, 10); - } + } + ``` + +### putImageData + +putImageData(imageData: Object, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth: number, dirtyHeight: number): void + +Puts the **ImageData** onto a rectangular area on the canvas. + +- Parameters + | Name | Type | Description | + | ----------- | ------ | ----------------------------- | + | imagedata | Object | **ImageData** object with pixels to put onto the canvas. | + | dx | number | X-axis offset of the rectangular area on the canvas. | + | dy | number | Y-axis offset of the rectangular area on the canvas. | + | dirtyX | number | X-axis offset of the upper left corner of the rectangular area relative to that of the source image.| + | dirtyY | number | Y-axis offset of the upper left corner of the rectangular area relative to that of the source image.| + | dirtyWidth | number | Width of the rectangular area to crop the source image. | + | dirtyHeight | number | Height of the rectangular area to crop the source image. | + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const test = this.$element('getImageData') + const ctx = test.getContext('2d'); + var imgData = ctx.createImageData(100, 100); + for (var i = 0; i < imgData.data.length; i += 4) { + imgData.data[i + 0] = 255; + imgData.data[i + 1] = 0; + imgData.data[i + 2] = 0; + imgData.data[i + 3] = 255; } - ``` - - ![](figures/en-us_image_0000001214463283.png) + ctx.putImageData(imgData, 10, 10); + } + } + ``` + ![en-us_image_0000001214463283](figures/en-us_image_0000001214463283.png) -### setLineDash +### setLineDash -setLineDash\(segments: Array\): void +setLineDash(segments: Array): void Sets the dash line style. -- Parameters - - - - - - - - - - - - -

Name

-

Type

-

Description

-

segments

-

Array

-

An array describing the interval of alternate line segments and length of spacing

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - ctx.arc(100, 75, 50, 0, 6.28); - ctx.setLineDash([10,20]); - ctx.stroke(); - } +- Parameters + | Name | Type | Description | + | -------- | ----- | -------------------- | + | segments | Array | An array describing the interval of alternate line segments and length of spacing.| + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + ctx.arc(100, 75, 50, 0, 6.28); + ctx.setLineDash([10,20]); + ctx.stroke(); } - ``` - - ![](figures/en-us_image_0000001214623229.png) + } + ``` + ![en-us_image_0000001214623229](figures/en-us_image_0000001214623229.png) -### getLineDash +### getLineDash -getLineDash\(\): Array +getLineDash(): Array Obtains the dash line style. -- Return values - - - - - - - - - - -

Type

-

Description

-

Array

-

Interval of alternate line segments and the length of spacing.

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - var info = ctx.getLineDash(); - } +- Return value + | Type | Description | + | ----- | ------------------------ | + | Array | An array describing the interval of alternate line segments and length of spacing.| + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + var info = ctx.getLineDash(); } - ``` - - -### transferFromImageBitmap7+ - -transferFromImageBitmap\(bitmap: ImageBitmap\): void - -Displays the specified **ImageBitmap** object. - -- Parameters - - - - - - - - - - - - -

Name

-

Type

-

Description

-

bitmap

-

ImageBitmap

-

ImageBitmap object to display.

-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow() { - const el =this.$refs.canvas; - const ctx = el.getContext('2d'); - var canvas = this.$refs.canvas.getContext('2d'); - var offscreen = new OffscreenCanvas(500,500); - var offscreenCanvasCtx = offscreen.getContext("2d"); - offscreenCanvasCtx.fillRect(0, 0, 200, 200); - - var bitmap = offscreen.transferToImageBitmap(); - canvas.transferFromImageBitmap(bitmap); - } + } + ``` + +### transferFromImageBitmap7+ + +transferFromImageBitmap(bitmap: ImageBitmap): void + +Displays the specified **ImageBitmap** object. + +- Parameters + | Name | Type | Description | + | ------ | ----------- | ------------------ | + | bitmap | ImageBitmap | **ImageBitmap** object to display.| + +- Example + ``` + +
+ +
+ ``` + + ``` + //xxx.js + export default { + onShow() { + const el =this.$refs.canvas; + const ctx = el.getContext('2d'); + var canvas = this.$refs.canvas.getContext('2d'); + var offscreen = new OffscreenCanvas(500,500); + var offscreenCanvasCtx = offscreen.getContext("2d"); + offscreenCanvasCtx.fillRect(0, 0, 200, 200); + + var bitmap = offscreen.transferToImageBitmap(); + canvas.transferFromImageBitmap(bitmap); } - ``` - - ![](figures/en-us_image_0000001168984882.png) + } + ``` + ![en-us_image_0000001168984882](figures/en-us_image_0000001168984882.png) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md index f686f9a01011f7afb704d3f10d5fadc7bd521ee3..4eb8cdcfc62dd32693f12dd94a046c5991bb73a2 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md @@ -2,6 +2,7 @@ > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. @@ -90,7 +91,7 @@ Sets the position of the caret. ``` @Entry @Component -struct TextAreaExample2 { +struct TextAreaExample1 { @State text: string = '' build() { Column() { @@ -126,7 +127,7 @@ struct TextAreaExample2 { ``` @Entry @Component -struct TextAreaTest { +struct TextAreaExample2 { controller: TextAreaController = new TextAreaController() build() { Column() { diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md index f91e78172298ab17e0cb2b4be62304eff49901ff..0bb567a4ab037272e73c62c7dfe75a1df736c046 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md @@ -2,6 +2,7 @@ > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. @@ -23,50 +24,50 @@ None TextInput(value?:{placeholder?: string controller?: TextInputController}) - Parameters - | Name | Type | Mandatory | Default Value | Description | - | ----------------------- | ---------------------------------------- | --------- | ------------- | -------------------------------------- | - | placeholder | string | No | - | Text displayed when there is no input. | - | controller8+ | [TextInputController](#textinputcontroller8) | No | - | Text input controller. | + | Name | Type | Mandatory | Default Value | Description | + | -------- | -------- | -------- | -------- | -------- | + | placeholder | string | No | - | Text displayed when there is no input. | + | controller8+ | [TextInputController](#textinputcontroller8) | No | - | Text input controller. | ## Attributes In addition to universal attributes, the following attributes are supported. -| Name | Type | Default Value | Description | -| ------------------------ | ---------------------------------------- | ----------------- | ---------------------------------------- | -| type | InputType | InputType.Normal | Input box type. | -| placeholderColor | Color | - | Placeholder color. | -| placeholderFont | {
size?: Length,
weight?: number\|[FontWeight](ts-universal-attributes-text-style.md),
family?: string,
style?: [FontStyle](ts-universal-attributes-text-style.md)
} | - | Placeholder text style.
- **size**: font size. If the value is of the number type, the unit fp is used.
- **weight**: font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight.
- **family**: font family. Use commas (,) to separate multiple fonts, for example, **'Arial, sans-serif'**. The priority of the fonts is the sequence in which they are placed.
- **style**: font style. | -| enterKeyType | EnterKeyType | EnterKeyType.Done | How the Enter key is labeled. | -| caretColor | Color | - | Color of the caret (also known as the text insertion cursor). | -| maxLength8+ | number | - | Maximum number of characters in the text input. | -| inputFilter8+ | {
value: [ResourceStr](../../ui/ts-types.md)8+,
error?: (value: string)
} | - | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are ignored. The specified regular expression can match single characters, but not strings. Example: ^(? =.\*\d)(? =.\*[a-z])(? =.\*[A-Z]).{8,10}$. Strong passwords containing 8 to 10 characters cannot be filtered.
- **value**: indicates the regular expression to set.
- **error**: returns the ignored content when regular expression matching fails. | +| Name | Type | Default Value | Description | +| -------- | -------- | -------- | -------- | +| type | InputType | InputType.Normal | Input box type. | +| placeholderColor | Color | - | Placeholder color. | +| placeholderFont | {
size?: Length,
weight?: number\|[FontWeight](ts-universal-attributes-text-style.md),
family?: string,
style?: [FontStyle](ts-universal-attributes-text-style.md)
} | - | Placeholder text style.
- **size**: font size. If the value is of the number type, the unit fp is used.
- **weight**: font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight.
- **family**: font family. Use commas (,) to separate multiple fonts, for example, **'Arial, sans-serif'**. The priority of the fonts is the sequence in which they are placed.
- **style**: font style. | +| enterKeyType | EnterKeyType | EnterKeyType.Done | How the Enter key is labeled. | +| caretColor | Color | - | Color of the caret (also known as the text insertion cursor). | +| maxLength8+ | number | - | Maximum number of characters in the text input. | +| inputFilter8+ | {
value: [ResourceStr](../../ui/ts-types.md)8+,
error?: (value: string)
} | - | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are ignored. The specified regular expression can match single characters, but not strings. Example: ^(? =.\*\d)(? =.\*[a-z])(? =.\*[A-Z]).{8,10}$. Strong passwords containing 8 to 10 characters cannot be filtered.
- **value**: indicates the regular expression to set.
- **error**: returns the ignored content when regular expression matching fails. | - EnterKeyType enums - | Name | Description | - | ------------------- | ---------------------------------- | - | EnterKeyType.Go | The Enter key is labeled "Go." | - | EnterKeyType.Search | The Enter key is labeled "Search." | - | EnterKeyType.Send | The Enter key is labeled "Send." | - | EnterKeyType.Next | The Enter key is labeled "Next." | - | EnterKeyType.Done | The Enter key is labeled "Done." | + | Name | Description | + | -------- | -------- | + | EnterKeyType.Go | The Enter key is labeled "Go." | + | EnterKeyType.Search | The Enter key is labeled "Search." | + | EnterKeyType.Send | The Enter key is labeled "Send." | + | EnterKeyType.Next | The Enter key is labeled "Next." | + | EnterKeyType.Done | The Enter key is labeled "Done." | - InputType enums - | Name | Description | - | ------------------ | ------------------------- | - | InputType.Normal | Normal input mode. | - | InputType.Password | Password input mode. | - | InputType.Email | Email address input mode. | - | InputType.Number | Digit input mode. | + | Name | Description | + | -------- | -------- | + | InputType.Normal | Normal input mode. | + | InputType.Password | Password input mode. | + | InputType.Email | Email address input mode. | + | InputType.Number | Digit input mode. | ### TextInputController8+ Implements the controller of the **<TextInput>** component. -| Name | Description | -| --------------------------------- | ---------------------------------------- | +| Name | Description | +| -------- | -------- | | caretPosition(value: number):void | Position of the input cursor.
**value**: indicates the length from the start of the string to the position where the input cursor is located. | @@ -85,16 +86,16 @@ caretPosition(value: number): void Sets the cursor in a specified position. - Parameters - | Name | Type | Mandatory | Default Value | Description | - | ----- | ------ | --------- | ------------- | ---------------------------------------- | - | value | number | Yes | - | Position of the input cursor.
**value**: indicates the length from the start of the string to the position where the input cursor is located. | + | Name | Type | Mandatory | Default Value | Description | + | -------- | -------- | -------- | -------- | -------- | + | value | number | Yes | - | Position of the input cursor.
**value**: indicates the length from the start of the string to the position where the input cursor is located. | ## Events -| Name | Description | -| ---------------------------------------- | ---------------------------------------- | -| onChange(value: string) => void | Triggered when the input changes. | +| Name | Description | +| -------- | -------- | +| onChange(value: string) => void | Triggered when the input changes. | | onSubmit(callback: (enterKey: EnterKeyType) => void) | Triggered when the Enter key on the physical or soft keyboard is pressed. | | onEditChanged(callback: (isEditing: boolean) => void)(deprecated) | Triggered when the input status changes. | | onEditChange(callback: (isEditing: boolean) => void) 8+ | Triggered when the input status changes. | @@ -112,7 +113,7 @@ Sets the cursor in a specified position. ``` @Entry @Component -struct TextAreaExample2 { +struct TextInputExample1 { @State text: string = '' build() { @@ -147,7 +148,7 @@ struct TextAreaExample2 { ``` @Entry @Component -struct TextInputTest { +struct TextInputExample2 { @State text: string = '' controller: TextInputController = new TextInputController() build() { diff --git a/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md b/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md index d0002ed9e23d81e0318212e3485a64d78f5c6cae..1395a2cf8dbf0ed99d20c74ab65d211df9f346c2 100644 --- a/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md @@ -1,7 +1,8 @@ -# OffscreenCanvasRenderingConxt2D +# OffscreenCanvasRenderingContext2D > ![icon-note.gif](public_sys-resources/icon-note.gif) **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. diff --git a/en/application-dev/ui/ui-ts-creating-simple-page.md b/en/application-dev/ui/ui-ts-creating-simple-page.md index 9d7054cc4dc17ee2e869f66e0711524f83e6fd93..4e9ee4b92152eade3066c4a79cb328cf8b998a57 100644 --- a/en/application-dev/ui/ui-ts-creating-simple-page.md +++ b/en/application-dev/ui/ui-ts-creating-simple-page.md @@ -1,13 +1,13 @@ # Creating a Simple Page -In this section, we will develop an infographic food details page, by building custom components through the container components <Stack> and <Flex> as well as basic components <Image> and <Text>. +In this section, we will develop an infographic food details page, by building custom components through the container components **\** and **\** as well as basic components **\** and **\**. ## Building the Stack Layout 1. Create a food name. - Delete the code of the build method in the project template, create a <Stack> component, and place the <Text> component in the braces of the <Stack> component so that the <Text> component becomes a child component of the <Stack> component. A <Stack> component consists of one or more child components. The latter child component overwrites the former one. + Delete the code of the build method in the project template, create a <Stack> component, and place the **\** component in the braces of the **\** component so that the <Text> component becomes a child component of the <Stack> component. A **\** component consists of one or more child components. The latter child component overwrites the former one. ``` @Entry @@ -26,7 +26,7 @@ In this section, we will develop an infographic food details page, by building c ![en-us_image_0000001222967780](figures/en-us_image_0000001222967780.png) 2. Display food pictures. - Create an <Image> component and specify a URL for it. The <Image> and <Text> components are mandatory. To display the <Text> component above the <Image> component, you need to declare the <Image> component first. Image resources are stored in the rawfile folder in resources. When referencing the resources in the rawfile folder, use the `"$rawfile('filename')"` format, where filename indicates the relative path of the file in the rawfile folder. Currently, `$rawfile` only allows the <Image> component to reference image resources. + Create an **\** component and specify a URL for it. The **\** and **\** components are mandatory. To display the **\** component above the **\** component, you need to declare the **\** component first. Image resources are stored in the **rawfile** folder in **resources**. When referencing the resources in the **rawfile** folder, use the `"$rawfile('filename')"` format, where filename indicates the relative path of the file in the **rawfile** folder. Currently, `$rawfile` only allows the **\** component to reference image resources. ``` @Entry @@ -137,9 +137,9 @@ In this section, we will develop an infographic food details page, by building c ![en-us_image_0000001222967772](figures/en-us_image_0000001222967772.png) -7. Adjust the left and bottom margin of the <Text> component. Margin is a shorthand attribute. You can specify the margins of the four edges in a unified manner or separately. The configuration method is as follows: - 1. When the parameter is set to Length, the outer margins of the four edges are specified. For example, **margin(20)** indicates that the outer margins of the top, right, bottom, and left edges are all 20. - 2. **{top?: Length, right?: Length, bottom?: Length, left?:Length}** specifies the margins of the four edges. For example, **margin({ left: 26, bottom: 17.4 })** indicates that the left margin is 26 and the bottom margin is 17.4. +7. Adjust the left and bottom margin of the **\** component. **Margin** is a shorthand attribute. You can specify the margins of the four edges in a unified manner or separately. The configuration method is as follows: + 1. To set the margins of the four edges in a unified manner, use the **Margin(Length)** format. For example, **margin(20)** indicates that the outer margins of the top, right, bottom, and left edges are all 20. + 2. To set the margins of the four edges separately, use the **{top?: Length, right?: Length, bottom?: Length, left?:Length}** format. For example, **margin({ left: 26, bottom: 17.4 })** indicates that the left margin is 26 and the bottom margin is 17.4. ``` @@ -163,7 +163,8 @@ In this section, we will develop an infographic food details page, by building c ![en-us_image_0000001222967776](figures/en-us_image_0000001222967776.png) -8. Adjust the structure between components and semanticize component names. Create the FoodDetail page entry component, create a column in **FoodDetail**, and set the alignment to **alignItems(HorizontalAlign.Center)**. Change the name of the MyComponent component to FoodImageDisplay, which is a child component of the FoodDetail component. +8. Adjust the structure between components and semanticize component names. Create the FoodDetail page entry component, create a column in **FoodDetail**, and set the alignment to **alignItems(HorizontalAlign.Center)**. Change the name of the **MyComponent** component to **FoodImageDisplay**, which is a child component of the **FoodDetail** component. + A column is a container component whose child components are vertically arranged. It is a linear layout in essence. Therefore, only the alignment in the cross axis direction can be set. @@ -239,10 +240,11 @@ You can use the Flex layout to build a food composition table. In this way you d ``` 2. Create a Flex component to display two food composition categories in the tomato: Calories and Nutrition. - Calories contains information about calories. Nutrition contains information about protein, fat, carbohydrates, and vitamin C. - - Create the Calories class. Create a Flex component and set its height to 280, and the top, right, and left margins to 30. The Flex component contains three Text child components, which represent the category name (Calories), content name (Calories), and contain value (17 kcal), respectively. By default, child components in the Flex component are arranged horizontally. - + +Calories contains information about calories. Nutrition contains information about protein, fat, carbohydrates, and vitamin C. + +Create the Calories class. Create a Flex component and set its height to 280, and the top, right, and left margins to 30. The Flex component contains three Text child components, which represent the category name (Calories), content name (Calories), and contain value (17 kcal), respectively. By default, child components in the Flex component are arranged horizontally. + In the following example, code of FoodImageDisplay is omitted, and only code of ContentTable is provided. @@ -279,7 +281,7 @@ You can use the Flex layout to build a food composition table. In this way you d ![en-us_image_0000001267767869](figures/en-us_image_0000001267767869.png) -3. Adjust the layout and set the proportion (layoutWeight) of each part. Set the proportion of the category name to 1, and the total proportion of content name and content value to **2**. The content name and content value are in a same Flex, and the content name occupies all remaining space flexGrow(1). +3. Adjust the layout and set the proportion (layoutWeight) of each part. Set the proportion of the category name to **1**, and the total proportion of content name and content value to **2**. The content name and content value are in a same Flex, and the content name occupies all remaining space flexGrow(1). ``` @Component @@ -336,6 +338,7 @@ You can use the Flex layout to build a food composition table. In this way you d ![en-us_image_0000001267607901](figures/en-us_image_0000001267607901.png) 4. Create the **Nutrient** class in a similar process. Nutrition consists of four parts: Protein, Fat, Carbohydrates, and VitaminC. The names of the last three parts are omitted in the table and represented by spaces. + Set **FlexDirection.Column**, **FlexAlign.SpaceBetween**, and **ItemAlign.Start**. @@ -467,7 +470,7 @@ You can use the Flex layout to build a food composition table. In this way you d } ``` - When the IngredientItem API is called in the build method of ContentTable, this needs to be used to invoke the method in the scope of the component to distinguish the global method call. +When the ` IngredientItem` API is called in the build method of ContentTable, ` this ` needs to be used to invoke the method in the scope of the component to distinguish the global method call. ``` @@ -488,7 +491,7 @@ You can use the Flex layout to build a food composition table. In this way you d } ``` - The overall code of the ContentTable component is as follows: +The overall code of the ContentTable component is as follows: ``` @@ -537,6 +540,6 @@ You can use the Flex layout to build a food composition table. In this way you d } ``` - ![en-us_image_0000001222807792](figures/en-us_image_0000001222807792.png) +![en-us_image_0000001222807792](figures/en-us_image_0000001222807792.png) You've learned how to build a simple food details page. Read on to learn how to define the page layout and connection. diff --git a/en/application-dev/ui/ui-ts-layout-flex.md b/en/application-dev/ui/ui-ts-layout-flex.md index dc205b3a7bb1faeaa5367784cba16b8abd9f7660..740781cfaeade89a6701f4869acdf56925d9f9c4 100644 --- a/en/application-dev/ui/ui-ts-layout-flex.md +++ b/en/application-dev/ui/ui-ts-layout-flex.md @@ -8,7 +8,7 @@ The **\** component is used to create a flex layout. In a flex container c The available API is as follows: -Flex(options?: { direction?: FlexDirection, wrap?: FlexWrap, justifyContent?: FlexAlign, alignItems?: ItemAlign, alignContent?: FlexAlign }) +`Flex(options?: { direction?: FlexDirection, wrap?: FlexWrap, justifyContent?: FlexAlign, alignItems?: ItemAlign, alignContent?: FlexAlign })` The **direction** parameter defines the flex layout direction. The **justifyContent** parameter defines the alignment mode of child components in the flex layout direction. The **alignContent** parameter defines the alignment mode of child components in the vertical direction. The **wrap** parameter defines whether the content can wrap onto multiple lines. ## Flex Layout Direction @@ -16,7 +16,7 @@ The **direction** parameter defines the flex layout direction. The **justifyCont The flex layout has two directions, following two axes. The main axis is the axis along which the child components follow each other. The cross axis is the axis perpendicular to the main axis. The **direction** parameter establishes the main axis. The available options are as follows: - **FlexDirection.Row** (default value): The main axis runs along the row horizontally, and the child components start from the start edge of the main axis. - + ``` Flex({ direction: FlexDirection.Row }) { Text('1').width('33%').height(50).backgroundColor(0xF5DEB3) @@ -32,7 +32,7 @@ The flex layout has two directions, following two axes. The main axis is the axi ![en-us_image_0000001218579606](figures/en-us_image_0000001218579606.png) - **FlexDirection.RowReverse**: The main axis runs along the row horizontally, and the child components start from the end edge of the main axis, in a direction opposite to **FlexDirection.Row**. - + ``` Flex({ direction: FlexDirection.RowReverse }) { Text('1').width('33%').height(50).backgroundColor(0xF5DEB3) @@ -48,7 +48,7 @@ The flex layout has two directions, following two axes. The main axis is the axi ![en-us_image_0000001218739566](figures/en-us_image_0000001218739566.png) - **FlexDirection.Column**: The main axis runs along the column vertically, and the child components start from the start edge of the main axis. - + ``` Flex({ direction: FlexDirection.Column }) { Text('1').width('100%').height(50).backgroundColor(0xF5DEB3) @@ -64,7 +64,7 @@ The flex layout has two directions, following two axes. The main axis is the axi ![en-us_image_0000001263019457](figures/en-us_image_0000001263019457.png) - **FlexDirection.ColumnReverse**: The main axis runs along the column vertically, and the child components start from the end edge of the main axis, in a direction opposite to **FlexDirection.Column**. - + ``` Flex({ direction: FlexDirection.ColumnReverse }) { Text('1').width('100%').height(50).backgroundColor(0xF5DEB3) @@ -85,7 +85,7 @@ The flex layout has two directions, following two axes. The main axis is the axi By default, child components are laid out on a single line (also called an axis) in the flex container. Use the **wrap** parameter to set whether child components can wrap onto multiple lines. The available options are as follows: - **FlexWrap.NoWrap**: Child components are laid out on a single line. This may cause the child components to shrink to fit the container when the total width of the child components is greater than the width of the container. - + ``` Flex({ wrap: FlexWrap.NoWrap }) { Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) @@ -100,7 +100,7 @@ By default, child components are laid out on a single line (also called an axis) ![en-us_image_0000001263139409](figures/en-us_image_0000001263139409.png) - **FlexWrap.Wrap**: Child components can break into multiple lines. - + ``` Flex({ wrap: FlexWrap.Wrap }) { Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) @@ -115,7 +115,7 @@ By default, child components are laid out on a single line (also called an axis) ![en-us_image_0000001218419614](figures/en-us_image_0000001218419614.png) - **FlexWrap.WrapReverse**: Child components can break into multiple lines in the reverse order to the row. - + ``` Flex({ wrap: FlexWrap.WrapReverse}) { Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) @@ -138,7 +138,7 @@ By default, child components are laid out on a single line (also called an axis) Use the **justifyContent** parameter to set alignment of items on the main axis. The available options are as follows: - **FlexAlign.Start**: The items are aligned with each other toward the start edge of the container along the main axis. - + ``` Flex({ justifyContent: FlexAlign.Start }) { Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) @@ -153,7 +153,7 @@ Use the **justifyContent** parameter to set alignment of items on the main axis. ![en-us_image_0000001218259634](figures/en-us_image_0000001218259634.png) - **FlexAlign.Center**: The items are aligned with each other toward the center of the container along the main axis. The space between the first component and the main-start is the same as that between the last component and the main-end. - + ``` Flex({ justifyContent: FlexAlign.Center }) { Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) @@ -168,7 +168,7 @@ Use the **justifyContent** parameter to set alignment of items on the main axis. ![en-us_image_0000001218579608](figures/en-us_image_0000001218579608.png) - **FlexAlign.End**: The items are aligned with each other toward the end edge of the container along the main axis. - + ``` Flex({ justifyContent: FlexAlign.End }) { Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) @@ -183,7 +183,7 @@ Use the **justifyContent** parameter to set alignment of items on the main axis. ![en-us_image_0000001218739568](figures/en-us_image_0000001218739568.png) - **FlexAlign.SpaceBetween**: The items are evenly distributed within the container along the main axis. The first item is aligned with the main-start, the last item is aligned with the main-end, and the remaining items are distributed so that the space between any two adjacent items is the same. - + ``` Flex({ justifyContent: FlexAlign.SpaceBetween }) { Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) @@ -198,7 +198,7 @@ Use the **justifyContent** parameter to set alignment of items on the main axis. ![en-us_image_0000001263019461](figures/en-us_image_0000001263019461.png) - **FlexAlign.SpaceAround**: The items are evenly distributed within the container along the main axis. The space between the first item and main-start, and that between the last item and cross-main are both half the size of the space between two adjacent items. - + ``` Flex({ justifyContent: FlexAlign.SpaceAround }) { Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) @@ -213,7 +213,7 @@ Use the **justifyContent** parameter to set alignment of items on the main axis. ![en-us_image_0000001263339461](figures/en-us_image_0000001263339461.png) - **FlexAlign.SpaceEvenly**: The items are equally distributed along the main axis. The space between the first item and main-start, the space between the last item and main-end, and the space between two adjacent items are the same. - + ``` Flex({ justifyContent: FlexAlign.SpaceEvenly }) { Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) @@ -233,7 +233,7 @@ Use the **justifyContent** parameter to set alignment of items on the main axis. Use the **alignItems** parameter to set alignment of items on the cross axis. The available options are as follows: - **ItemAlign.Auto**: The items are automatically aligned in the flex container. - + ``` Flex({ alignItems: ItemAlign.Auto }) { Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) @@ -248,7 +248,7 @@ Use the **alignItems** parameter to set alignment of items on the cross axis. Th ![en-us_image_0000001218419616](figures/en-us_image_0000001218419616.png) - **ItemAlign.Start**: The items are aligned with the start edge of the container along the cross axis. - + ``` Flex({ alignItems: ItemAlign.Start }) { Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) @@ -263,7 +263,7 @@ Use the **alignItems** parameter to set alignment of items on the cross axis. Th ![en-us_image_0000001263259401](figures/en-us_image_0000001263259401.png) - **ItemAlign.Start**: The items are aligned with the center of the container along the cross axis. - + ``` Flex({ alignItems: ItemAlign.Center }) { Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) @@ -278,7 +278,7 @@ Use the **alignItems** parameter to set alignment of items on the cross axis. Th ![en-us_image_0000001218259636](figures/en-us_image_0000001218259636.png) - **ItemAlign.End**: The items are aligned with the end edge of the container along the cross axis. - + ``` Flex({ alignItems: ItemAlign.End }) { Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) @@ -293,7 +293,7 @@ Use the **alignItems** parameter to set alignment of items on the cross axis. Th ![en-us_image_0000001218579610](figures/en-us_image_0000001218579610.png) - **ItemAlign.Stretch**: The items are stretched along the cross axis. If no constraints are set, the items are stretched to fill the size of the container on the cross axis. - + ``` Flex({ alignItems: ItemAlign.Stretch }) { Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) @@ -308,7 +308,7 @@ Use the **alignItems** parameter to set alignment of items on the cross axis. Th ![en-us_image_0000001218739570](figures/en-us_image_0000001218739570.png) - **ItemAlign.Baseline**: The items are aligned at the baseline of the cross axis. - + ``` Flex({ alignItems: ItemAlign.Baseline }) { Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) diff --git a/en/application-dev/ui/ui-ts-layout-grid-container.md b/en/application-dev/ui/ui-ts-layout-grid-container.md index c1e16b6db398b07d7edfd8b4551853709f73d3e2..62c6762258110f519c9866165ea3007b9936fd41 100644 --- a/en/application-dev/ui/ui-ts-layout-grid-container.md +++ b/en/application-dev/ui/ui-ts-layout-grid-container.md @@ -8,22 +8,22 @@ As a tool to provide layout auxiliary lines, the grid system is handy in graphic 2. Provides a unified positioning method for the system to ensure layout consistency among modules on different devices. 3. Provides a flexible spacing adjustment method for applications to keep up with layout in special scenarios. -To implement the grid layout, the declarative paradigm provides the \ component, together with the universal attribute useSizeType of its child components. +To implement grid layout, the declarative paradigm provides the [GridContainer](../reference/arkui-ts/ts-container-gridcontainer.md) grid container component, which works with the common attribute useSizeType of its subcomponents to implement grid layout. ## Grid System -The grid system works in terms of columns, margins, and gutters. +The grid system works in terms of gutter, margin, and column. ![en-us_image_0000001217236574](figures/en-us_image_0000001217236574.png) -1. Gutters: +1. Gutter: Spacing between elements. You can define different clutter values for different device sizes as part of the overall grid layout specifications. For better results, make sure the gutter is not greater than the margin. -2. Margins: +2. Margin: Spacing around an item in the grid container. You can define different margin values for different device sizes as part of the overall grid layout specifications. -3. Columns: - Main tool for positioning items in the grid layout. The grid container is divided into different columns based on the device size. The width of each column is calculated based on the total number of columns while respecting the margin and clutter specifications. +3. Column: + Main tool for positioning items in the grid layout. The grid container is divided into various numbers of columns based on the device size. The width per column is calculated based on the total number of columns while respecting the margin and clutter specifications. ### Grid Breakpoints @@ -32,15 +32,13 @@ Breakpoints in the grid system are set in terms of the device's screen pixel den Depending on the screen width, devices are classified into different width types. The table below provides the mappings of the grid breakpoint ranges, device width types, default total number of columns, margins, and gutters. -Grid layout - -| Grid Breakpoint Range| Device Width Type| Description| Columns| Gutter| Margin| -| -------- | -------- | -------- | -------- | -------- | -------- | -| 0 < Device screen width < 320 vp | XS | Device of the minimum size.| 2 | 12 vp| 12 vp| -| 320 vp <= Device screen width < 600 vp| SM | Small-sized device.| 4 | 24 vp| 24 vp| -| 600 vp lt;= Device screen width lt;840 vp| MD | Medium-sized device.| 8 | 24 vp| 32 vp| -| 840 vp <= Device screen width| LG | Large-sized device.| 12 | 24 vp| 48 vp| +| Grid Breakpoint Range | Device Width Type| Description | columns | gutter | margin | +| ----------------------- | ------ | --------- | ------- | ------ | ------ | +| 0 < Device screen width < 320 vp | XS | Device of the minimum size.| 2 | 12 vp | 12 vp | +| 320 vp <= Horizontal width < 600 vp| SM | Small-sized device. | 4 | 24 vp | 24 vp | +| 600 vp <= Horizontal width < 840 vp| MD | Medium-sized device.| 8 | 24 vp | 32 vp | +| 840 vp <= Device screen width | LG | Large-sized device. | 12 | 24 vp | 48 vp | ## Usage @@ -48,41 +46,44 @@ Create a grid container, define the grid layout, and set the number of columns f ### Creating a Grid Container -Use the **GridContainer(options?: { columns?: number | 'auto', sizeType?: SizeType, gutter?: Length, margin?: Length})** API to create a grid container. All child components in the grid container follow the grid layout. +Use the `GridContainer(options?: { columns?: number | 'auto', sizeType?: SizeType, gutter?: Length, margin?: Length})` API to create a grid container. All child components in the grid container follow the grid layout. -Use the **columns**, **gutter**, and **margin** parameters to define your grid layout. In the sample below, the grid container is divided into six columns, with the gutter (spacing between columns) of 10 vp and the margin (spacing around a column) of 20 vp. -``` -GridContainer({ columns: 6, gutter: 10, margin: 20 }) {} -``` -In the sample below, the grid container does not have any parameter set. In this case, it follows the default layout, as in the case when sizeType is set to SizeType.Auto. +- Use the **columns**, **gutter**, and **margin** parameters to define your grid layout. In the sample below, the grid container is divided into six columns, with the gutter (spacing between columns) of 10 vp and the margin (spacing around a column) of 20 vp. -``` -GridContainer() {} -``` -On a small-sized device (**SizeType.SM**), the grid container is divided into four columns by default, with the gutter of 24 vp and the margin of 24 vp. On a medium-sized device (**SizeType.MD**), the grid container is divided into eight columns by default, with the gutter of 24 vp and the margin of 32 vp. + ``` + GridContainer({ columns: 6, gutter: 10, margin: 20 }) {} + ``` + In the sample below, the grid container does not have any parameter set. In this case, it follows the default layout, as in the case when sizeType is set to SizeType.Auto. + ``` + GridContainer() {} + ``` -You can also use **sizeType** to configure child components in the grid container to follow the grid settings for a specific device width type, as shown below: + On a small-sized device (**SizeType.SM**), the grid container is divided into four columns by default, with the gutter of 24 vp and the margin of 24 vp. On a medium-sized device (**SizeType.MD**), the grid container is divided into eight columns by default, with the gutter of 24 vp and the margin of 32 vp. -``` -GridContainer({ sizeType: SizeType.SM) { - Row() { - Text('1') - .useSizeType({ - xs: { span: 2}, - sm: { span: 3, offset: 1 }, - md: { span: 6, offset: 2 }, - lg: { span: 8, offset: 2 }, - }) - } -} -``` -In the preceding example, the **\** component uses the grid setting of the **SizeType.SM** type regardless of the actual width type of the device. That is, the **\** component occupies three columns and is placed in the first column. +- You can also use **sizeType** to configure child components in the grid container to follow the grid settings for a specific device width type, as shown below: + + ``` + GridContainer({ sizeType: SizeType.SM) { + Row() { + + Text('1') + .useSizeType({ + xs: { span: 2}, + sm: { span: 3, offset: 1 }, + md: { span: 6, offset: 2 }, + lg: { span: 8, offset: 2 }, + }) + } + } + ``` + + In the preceding example, the **\** component uses the grid setting of the **SizeType.SM** type regardless of the actual width type of the device. That is, the **\** component occupies three columns and is placed in the first column. ### Grid Settings of Child Components in the Grid Container -Use the universal attribute **useSizeType** to configure the positioning of child components in the grid container. span indicates the number of columns occupied by the child component. offset indicates the column offset, that is, the column where the component is located. The sample code is as follows: +Use the universal attribute **useSizeType** to configure the positioning of child components in the grid container. **span** indicates the number of columns occupied by the child component. **offset** indicates the column offset, that is, the column where the component is located. The sample code is as follows: ``` GridContainer() { @@ -97,7 +98,7 @@ GridContainer() { } } ``` -In the preceding example, **sm: { span: 2, offset: 0 }** indicates that on a medium-sized device, the **\** component occupies three columns and is placed in the first column of the grid container. +In the preceding example, `sm: { span: 2, offset: 0 }` indicates that on a medium-sized device, the **\** component occupies three columns and is placed in the first column of the grid container. ## Example Scenario The grid layout helps ensure proper display of components among different device width types, eliminating the hassle of writing a large amount of code for device compatibility. @@ -108,8 +109,8 @@ The grid layout helps ensure proper display of components among different device struct GridContainerExample { build() { Column({ space: 5 }) { - GridContainer({ columns: 6, sizeType: SizeType.Auto, gutter: 10, margin: 20 }) { - Row() { + GridContainer({ columns: 6 }) { + Flex({justifyContent:FlexAlign.SpaceAround}) { Text('1') .useSizeType({ xs: { span: 2, offset: 0 }, @@ -120,18 +121,18 @@ struct GridContainerExample { .height(100).backgroundColor(0x4682B4).textAlign(TextAlign.Center) Text('2') .useSizeType({ - xs: { span: 2, offset: 2 }, - sm: { span: 2, offset: 2 }, - md: { span: 4, offset: 1 }, - lg: { span: 4, offset: 1 }, + xs: { span: 2, offset: 0 }, + sm: { span: 2, offset: 0 }, + md: { span: 4, offset: 0 }, + lg: { span: 4, offset: 0 }, }) .height(100).backgroundColor(0x46F2B4).textAlign(TextAlign.Center) Text('3') .useSizeType({ - xs: { span: 2, offset: 4 }, - sm: { span: 2, offset: 4 }, - md: { span: 1, offset: 5 }, - lg: { span: 1, offset: 5 }, + xs: { span: 2, offset: 0 }, + sm: { span: 2, offset: 0 }, + md: { span: 1, offset: 0 }, + lg: { span: 1, offset: 0 }, }) .height(100).backgroundColor(0x46A2B4).textAlign(TextAlign.Center) } @@ -148,4 +149,5 @@ Effect on a small-sized device (**SizeType.SM**): ![en-us_image_0000001218108718](figures/en-us_image_0000001218108718.png) Effect on a medium-sized device (**SizeType.MD**): -![en-us_image_0000001262748569](figures/en-us_image_0000001262748569.png) + +![en-us_image_0000001262748569](figures/en-us_image_0000001262748569.png) \ No newline at end of file diff --git a/en/application-dev/ui/ui-ts-layout-mediaquery.md b/en/application-dev/ui/ui-ts-layout-mediaquery.md index fa4a03382cd5c851d46f951c60949b64139bc4df..e448fb8fce7b3b90edb0bab5b607b326616ba779 100644 --- a/en/application-dev/ui/ui-ts-layout-mediaquery.md +++ b/en/application-dev/ui/ui-ts-layout-mediaquery.md @@ -15,11 +15,11 @@ Invoke the **mediaquery** API to set the media query condition and the callback, First, import the mediaquery module, as shown below: ``` - import mediaquery from '@ohos.mediaquery' +import mediaquery from '@ohos.mediaquery' ``` Then, use the **matchMediaSync** API to set the media query condition and save the returned listener, as shown below: ``` - listener = mediaquery.matchMediaSync('(orientation: landscape)') +listener = mediaquery.matchMediaSync('(orientation: landscape)') ``` Finally, register the callback using the saved listener, and change the page layout or implement service logic in the callback. When the media query condition is matched, the callback is triggered. The sample code is as follows: ``` @@ -38,16 +38,20 @@ listener.on('change', onPortrait) [media-type] [and|not|only] [(media-feature)] ``` Examples are as follows: -screen and (round-screen: true) // This condition is met when the device screen is round. -(max-height: 800) // The condition is met when the height is less than 800. -(height <= 800) // The condition is met when the height is less than 800. -screen and (device-type: tv) or (resolution < 2) // This is a multi-condition complex statement query containing multiple media features. + + ` screen and (round-screen: true) ` // The query is valid when the device screen is round. + + ` (max-height: 800) ` // The query is valid when the height does not exceed 800. + + ` (height <= 800) ` // The query is valid when the height does not exceed 800. + + ` screen and (device-type: tv) or (resolution < 2) ` // The query is valid only when all media features are true. ### media-type -| Type | Description | -| ------ | ---------------------------------------- | -| screen | Media query based on screen-related parameters. | +| Type | Description | +| ------ | -------------- | +| screen | Media query based on screen-related parameters.| ### Media Logic Operation (and|not|only) @@ -56,48 +60,48 @@ You can use logical operators (**and**, **or**, **not**, and **only**) to compos **Table 1** Media logical operators -| Type | Description | +| Type | Description | | -------- | ---------------------------------------- | -| and | The **and** operator is used to combine multiple media features into one media query, in a logical AND operation. The query is valid only when all media features are true. It can also combine media types and media functions.
For example, **screen and (device-type: wearable) and (max-height: 600) ** indicates that the query is valid when the device type is wearable and the maximum height of the application is 600 pixel units. | -| not | The **not** operator is used to perform a logical negation for a media query. **true** is returned if the query condition is not met. Otherwise, **false** is returned. In a media query list, logical negation is performed only for the media query using the **not** operator.
For example, **not screen and (min-height: 50) and (max-height: 600) ** indicates that the query is valid when the height of the application is less than 50 pixel units or greater than 600 pixel units.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> When the **not** operator is used, the media type must be specified. | -| only | The **only** operator applies the selected style only when the entire expression is matched. It can be used to prevent ambiguity on browsers of earlier versions. The statements that contain both media types and media features produce ambiguity when they are received by some browsers of earlier versions. For example:
screen and (min-height: 50)
The browsers of earlier versions would mislead this sentence into screen, causing the fact that the specified style is applied when only the media type is matched. In this case, the **only** operator can be used to avoid this problem.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> When the **only** operator is used, the media type must be specified. | -| ,(comma) | The **or** operator is used to combine multiple media features into one media query, in a logical OR operation. The query is valid if a media feature is true. The effect of a comma operator is equivalent to that of the **or** operator.
For example, **screen and (min-height: 1000),  (round-screen: true) ** indicates that the query is valid when the minimum height of the application is 1000 pixel units or the device screen is round. | -| or | The **or** operator is used to combine multiple media features into one media query, in a logical OR operation. The query is valid if a media feature is true.
For example, **screen and (max-height: 1000) or  (round-screen: true)** indicates that the query is valid when the maximum height of the application is 1000 pixel units or the device screen is round. | +| and | The **and** operator is used to combine multiple media features into one media query, in a logical AND operation. The query is valid only when all media features are true. It can also combine media types and media functions.
For example, **screen and (device-type: wearable) and (max-height: 600) ** indicates that the query is valid when the device type is wearable and the maximum height of the application is 600 pixel units.| +| not | The **not** operator is used to perform a logical negation for a media query. **true** is returned if the query condition is not met. Otherwise, **false** is returned. In a media query list, logical negation is performed only for the media query using the **not** operator.
For example, **not screen and (min-height: 50) and (max-height: 600) ** indicates that the query is valid when the height of the application is less than 50 pixel units or greater than 600 pixel units.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> When the **not** operator is used, the media type must be specified.| +| only | The **only** operator applies the selected style only when the entire expression is matched. It can be used to prevent ambiguity on browsers of earlier versions. The statements that contain both media types and media features produce ambiguity when they are received by some browsers of earlier versions. For example:
screen and (min-height: 50)
The browsers of earlier versions would mislead this sentence into screen, causing the fact that the specified style is applied when only the media type is matched. In this case, the **only** operator can be used to avoid this problem.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> When the **only** operator is used, the media type must be specified.| +| ,(comma) | The **or** operator is used to combine multiple media features into one media query, in a logical OR operation. The query is valid if a media feature is true. The effect of a comma operator is equivalent to that of the **or** operator.
For example, **screen and (min-height: 1000),  (round-screen: true) ** indicates that the query is valid when the minimum height of the application is 1000 pixel units or the device screen is round.| +| or | The **or** operator is used to combine multiple media features into one media query, in a logical OR operation. The query is valid if a media feature is true.
For example, **screen and (max-height: 1000) or  (round-screen: true)** indicates that the query is valid when the maximum height of the application is 1000 pixel units or the device screen is round.| -At MediaQuery Level 4, range query is imported so that you can use the operators including <=, >=, <, and > besides the **max-** and **min-** operators. +At MediaQuery Level 4, range query is imported so that you can use the operators including <=, >=, <, and > besides the max- and min-operators. **Table 2** Logical operators for range query -| Type | Description | +| Type | Description | | ----- | ---------------------------------------- | -| <= | Less than or equal to, for example, **screen and (50 <= height)**. | -| >= | Greater than or equal to, for example, **screen and (600 >= height)**. | -| < | Less than, for example, **screen and (50 < height)**. | -| > | Greater than, for example, **screen and (600 > height)**. | +| <= | Less than or equal to, for example, **screen and (50 <= height)**.| +| >= | Greater than or equal to, for example, **screen and (600 >= height)**.| +| < | Less than, for example, **screen and (50 < height)**.| +| > | Greater than, for example, **screen and (600 > height)**.| ### media-feature -| Type | Description | +| Type | Description | | ----------------- | ---------------------------------------- | -| height | Height of the display area on the application page. | -| min-height | Minimum height of the display area on the application page. | -| max-height | Maximum height of the display area on the application page. | -| width | Width of the display area on the app page. | -| min-width | Minimum width of the display area on the application page. | -| max-width | Maximum width of the display area on the application page. | -| resolution | Resolution of the device. The unit can be dpi, dppx, or dpcm.
- **dpi** indicates the number of physical pixels per inch. 1 dpi ≈ 0.39 dpcm.
- **dpcm** indicates the number of physical pixels per centimeter. 1 dpcm ≈ 2.54 dpi.
- **dppx** indicates the number of physical pixels in each pixel. (This unit is calculated based on this formula: 96 px = 1 inch, which is different from the calculation method of the px unit on the page.) 1 dppx = 96 dpi. | -| min-resolution | Minimum device resolution. | -| max-resolution | Maximum device resolution. | -| orientation | Screen orientation.
Options are as follows:
- orientation: portrait
- orientation: landscape | -| device-height | Height of the device. | -| min-device-height | Minimum height of the device. | -| max-device-height | Maximum height of the device. | -| device-width | Width of the device. | -| min-device-width | Minimum width of the device. | -| max-device-width | Maximum width of the device. | +| height | Height of the display area on the application page. | +| min-height | Minimum height of the display area on the application page. | +| max-height | Maximum height of the display area on the application page. | +| width | Width of the display area on the app page. | +| min-width | Minimum width of the display area on the application page. | +| max-width | Maximum width of the display area on the application page. | +| resolution | Resolution of the device. The unit can be dpi, dppx, or dpcm.
- **dpi** indicates the number of physical pixels per inch. 1 dpi ≈ 0.39 dpcm.
- **dpcm** indicates the number of physical pixels per centimeter. 1 dpcm ≈ 2.54 dpi.
- **dppx** indicates the number of physical pixels in each pixel. (This unit is calculated based on this formula: 96 px = 1 inch, which is different from the calculation method of the px unit on the page.) 1 dppx = 96 dpi.| +| min-resolution | Minimum device resolution. | +| max-resolution | Maximum device resolution. | +| orientation | Screen orientation.
Options are as follows:
- orientation: portrait
- orientation: landscape| +| device-height | Height of the device. | +| min-device-height | Minimum height of the device. | +| max-device-height | Maximum height of the device. | +| device-width | Width of the device. | +| min-device-width | Minimum width of the device. | +| max-device-width | Maximum width of the device. | | round-screen | Screen type. The value **true** means that the screen is round, and **false** means the opposite. | -| dark-mode | Whether the device is in dark mode. The value **true** means that the device is in dark mode, and **false** means the opposite. | +| dark-mode | Whether the device is in dark mode. The value **true** means that the device is in dark mode, and **false** means the opposite. | ## Example Scenario @@ -138,8 +142,14 @@ Use media queries to apply different content and styles to the page text when th } } ``` -When the device is in landscape orientation, the text content is displayed in landscape mode in the color of #FFD700.
+When the device is in landscape orientation, the text content is displayed in landscape mode in the color of #FFD700.
![en-us_image_0000001262954829](figures/en-us_image_0000001262954829.png) -When the device is not in landscape orientation, the text content is displayed in portrait mode in the color of #DB7093.
+When the device is not in landscape orientation, the text content is displayed in portrait mode in the color of #DB7093.
![en-us_image_0000001263074739](figures/en-us_image_0000001263074739.png) + +## Samples + +The following sample is provided to help you better understand how to develop the media query: + +- [`MediaQuery`: eTS Media Query (API 8)](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/MediaQuery)