提交 c584a6fc 编写于 作者: E ester.zhou

Update docs (11207)

Signed-off-by: Nester.zhou <ester.zhou@huawei.com>
上级 25aedacc
...@@ -21,7 +21,7 @@ Gauge(options:{value: number, min?: number, max?: number}) ...@@ -21,7 +21,7 @@ Gauge(options:{value: number, min?: number, max?: number})
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Current data value.| | value | number | Yes| Current value of the chart, that is, the position to which the pointer points in the chart. It is used as the initial value of the chart when the component is created.|
| min | number | No| Minimum value of the current data segment.<br>Default value: **0**| | min | number | No| Minimum value of the current data segment.<br>Default value: **0**|
| max | number | No| Maximum value of the current data segment.<br>Default value: **100**| | max | number | No| Maximum value of the current data segment.<br>Default value: **100**|
...@@ -31,10 +31,10 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -31,10 +31,10 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Description| | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| value | number | Value of the chart.<br>Default value: **0**| | value | number | Value of the chart. It can be dynamically changed.<br>Default value: **0**|
| startAngle | number | Start angle of the chart. The value 0 indicates 0 degrees, and a positive value indicates the clockwise direction.<br>Default value: **-150**| | startAngle | number | Start angle of the chart. The value **0** indicates 0 degrees, and a positive value indicates the clockwise direction.<br>Default value: **0**|
| endAngle | number | End angle of the chart. The value 0 indicates 0 degrees, and a positive value indicates the clockwise direction.<br>Default value: **150**| | endAngle | number | End angle of the chart. The value **0** indicates 0 degrees, and a positive value indicates the clockwise direction.<br>Default value: **360**|
| colors | Array&lt;ColorStop&gt; | Colors of the chart. Colors can be set for individual segments.| | colors | Array&lt;[ColorStop](#colorstop)&gt; | Colors of the chart. Colors can be set for individual segments.|
| strokeWidth | Length | Stroke width of the chart.| | strokeWidth | Length | Stroke width of the chart.|
## ColorStop ## ColorStop
...@@ -43,7 +43,7 @@ Describes a gradient stop. ...@@ -43,7 +43,7 @@ Describes a gradient stop.
| Name | Type | Description | | Name | Type | Description |
| --------- | -------------------- | ------------------------------------------------------------ | | --------- | -------------------- | ------------------------------------------------------------ |
| ColorStop | [[ResourceColor](ts-types.md#resourcecolor), number] | Type of the gradient stop. The first parameter specifies the color, and the second parameter specifies the offset, which ranges from 0 to 1.| | ColorStop | [[ResourceColor](ts-types.md#resourcecolor), number] | Type of the gradient stop. The first parameter indicates the color value. If it is set to a non-color value, the black color is used. The second parameter indicates the color weight. If it is set to a negative number or a non-numeric value, the color weight is 0, which means that the color is not displayed.|
## Example ## Example
...@@ -55,15 +55,30 @@ Describes a gradient stop. ...@@ -55,15 +55,30 @@ Describes a gradient stop.
@Component @Component
struct GaugeExample { struct GaugeExample {
build() { build() {
Column() { Column({ space: 20 }) {
Gauge({ value: 50, min: 0, max: 100 }) // Use the default value of min and max, which is 0-100, and the default values of startAngle and endAngle, which are 0 and 360, respectively.
.startAngle(210).endAngle(150) // Set the current value to 75.
.colors([[0x317AF7, 1], [0x5BA854, 1], [0xE08C3A, 1], [0x9C554B, 1], [0xD94838, 1]]) Gauge({ value: 75 })
.strokeWidth(20) .width(200).height(200)
.colors([[0x317AF7, 1], [0x5BA854, 1], [0xE08C3A, 1], [0x9C554B, 1]])
// Set the value parameter to 75 and the value attribute to 25. The attribute setting is used.
Gauge({ value: 75 })
.value(25) // If both the attribute and parameter are set, the parameter setting is used.
.width(200).height(200) .width(200).height(200)
.colors([[0x317AF7, 1], [0x5BA854, 1], [0xE08C3A, 1], [0x9C554B, 1]])
// A ring chart of 210 to 150 degrees
Gauge({ value: 30, min: 0, max: 100 })
.startAngle(210)
.endAngle(150)
.colors([[0x317AF7, 0.1], [0x5BA854, 0.2], [0xE08C3A, 0.3], [0x9C554B, 0.4]])
.strokeWidth(20)
.width(200)
.height(200)
}.width('100%').margin({ top: 5 }) }.width('100%').margin({ top: 5 })
} }
} }
``` ```
![en-us_image_0000001174422916](figures/en-us_image_0000001174422916.png) ![gauge](figures/gauge-image.png)
...@@ -27,7 +27,7 @@ Obtains an image from the specified source for subsequent rendering and display. ...@@ -27,7 +27,7 @@ Obtains an image from the specified source for subsequent rendering and display.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| src | string\| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Yes | Image source. Both local and online images are supported.<br>When using an image referenced using a relative path, for example, `Image("common/test.jpg")`, the **\<Image>** component cannot be called across bundles or modules. Therefore, you are advised to use `$r` to reference image resources that need to be used globally.<br>- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.<br>\- Base64 strings are supported. The value format is `data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data]`, where `[base64 data]` is a Base64 string.<br/>\- The value can also be a path starting with `dataability://`, which is used to access the image path provided by a Data ability. | | src | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Yes | Image source. Both local and online images are supported.<br>When using an image referenced using a relative path, for example, `Image("common/test.jpg")`, the **\<Image>** component cannot be called across bundles or modules. Therefore, you are advised to use `$r` to reference image resources that need to be used globally.<br>- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.<br>\- Base64 strings are supported. The value format is data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where [base64 data] is a Base64 string.<br/>\- Strings with the **datashare://path** prefix are supported, which are used to access the image path provided by a data ability.<br>\- Strings with the `file:///data/storage` prefix are supported, which are used to read image resources in the **files** folder in the installation directory of the application. Ensure that the files in the directory package path have the read permission.|
## Attributes ## Attributes
...@@ -35,15 +35,15 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -35,15 +35,15 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name | Type | Description | | Name | Type | Description |
| --------------------- | ------------------------------------------------------- | ------------------------------------------------------------ | | --------------------- | ------------------------------------------------------- | ------------------------------------------------------------ |
| alt | string \| [Resource](ts-types.md#resource)| Placeholder image displayed during loading. Both local and Internet URIs are supported. | | alt | string \| [Resource](ts-types.md#resource)| Placeholder image displayed during loading. Local images are supported. |
| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | Image scale mode.<br>Default value: **ImageFit.Cover** | | objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | Image scale mode.<br>Default value: **ImageFit.Cover** |
| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Whether the image is repeated.<br>Default value: **NoRepeat**<br>**NOTE**<br>This attribute is not applicable to SVG images.| | objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Whether the image is repeated.<br>Default value: **NoRepeat**<br>**NOTE**<br>This attribute is not applicable to SVG images.|
| interpolation | [ImageInterpolation](#imageinterpolation) | Interpolation effect of the image. This attribute is intended to alleviate aliasing that occurs when a low-definition image is zoomed in.<br>Default value: **ImageInterpolation.None**<br>**NOTE**<br>This attribute is not applicable to SVG images.<br>This attribute is not applicable to **PixelMap** objects.| | interpolation | [ImageInterpolation](#imageinterpolation) | Interpolation effect of the image. This attribute is intended to alleviate aliasing that occurs when a low-definition image is zoomed in.<br>Default value: **ImageInterpolation.None**<br>**NOTE**<br>This attribute is not applicable to SVG images and **PixelMap** objects. |
| renderMode | [ImageRenderMode](#imagerendermode) | Rendering mode of the image.<br>Default value: **ImageRenderMode.Original**<br>**NOTE**<br>This attribute is not applicable to SVG images.| | renderMode | [ImageRenderMode](#imagerendermode) | Rendering mode of the image.<br>Default value: **ImageRenderMode.Original**<br>**NOTE**<br>This attribute is not applicable to SVG images.|
| sourceSize | {<br>width: number,<br>height: number<br>} | Size of the decoded image. The original image is decoded into a **pixelMap** of the specified size, in px.<br>**NOTE**<br>This attribute is not applicable to **PixelMap** objects.| | sourceSize | {<br>width: number,<br>height: number<br>} | Size of the decoded image. The original image is decoded into a **pixelMap** of the specified size, in px.<br>**NOTE**<br>This attribute is not applicable to **PixelMap** objects.|
| matchTextDirection | boolean | Whether to display the image in the system language direction. When this parameter is set to true, the image is horizontally flipped in the right-to-left (RTL) language context.<br>Default value: **false** | | matchTextDirection | boolean | Whether to display the image in the system language direction. When this parameter is set to true, the image is horizontally flipped in the right-to-left (RTL) language context.<br>Default value: **false** |
| fitOriginalSize | boolean | Whether to fit the component to the original size of the image source when the component size is not set.<br>Default value: **true** | | fitOriginalSize | boolean | Whether to fit the component to the original size of the image source when the component size is not set.<br>Default value: **false** |
| fillColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color of the image. This attribute only applies to an SVG image. Once set, the fill color will replace that of the SVG image.| | fillColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color. This attribute only applies to an SVG image. Once set, the fill color will replace that of the SVG image.|
| autoResize | boolean | Whether to resize the image source used for drawing based on the size of the display area during image decoding. This resizing can help reduce the memory usage.<br>Default value: **true**| | autoResize | boolean | Whether to resize the image source used for drawing based on the size of the display area during image decoding. This resizing can help reduce the memory usage.<br>Default value: **true**|
| syncLoad<sup>8+</sup> | boolean | Whether to load the image synchronously. By default, the image is loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder diagram is not displayed.<br>Default value: **false**| | syncLoad<sup>8+</sup> | boolean | Whether to load the image synchronously. By default, the image is loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder diagram is not displayed.<br>Default value: **false**|
| copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether the image can be copied. (SVG images cannot be copied.)<br>When **copyOption** is set to a value other than **CopyOptions.None**, the image can be copied in various manners, such as long pressing, right-clicking, or pressing Ctrl+C.<br>Default value: **CopyOptions.None**| | copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether the image can be copied. (SVG images cannot be copied.)<br>When **copyOption** is set to a value other than **CopyOptions.None**, the image can be copied in various manners, such as long pressing, right-clicking, or pressing Ctrl+C.<br>Default value: **CopyOptions.None**|
...@@ -51,7 +51,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -51,7 +51,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
> **NOTE** > **NOTE**
> >
> To use the shortcut keys to copy an **\<Image>** component, first set the **focusable** and **focusOnTouch** attributes of the component to **true** so that it can have focus. > To use shortcut keys to copy the image, the image must be in focus. To enable the image to gain focus, set both the **focusable** and **focusOnTouch** attributes to **true**.
> For SVG images, only the following tags are included in the supported list: **svg**, **rect**, **circle**, **ellipse**, **path**, **line**, **polyline**, **polygon**, **animate**, **animateMotion**, and **animateTransform**.
### ImageInterpolation ### ImageInterpolation
...@@ -74,10 +75,10 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -74,10 +75,10 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
In addition to the [universal events](ts-universal-events-click.md), the following events are supported. In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
| Name | Description | | Name | Description |
| ---------------------------------------- | ---------------------------------------- | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| onComplete(callback: (event?: { width: number, height: number, componentWidth: number,<br> componentHeight: number, loadingStatus: number }) =&gt; void) | Triggered when an image is successfully loaded. The size of the loaded image is returned.<br>- **width**: width of the image, in pixels.<br>- **height**: height of the image, in pixels.<br>- **componentWidth**: width of the container component, in pixels.<br>- **componentHeight**: height of the container component, in pixels.<br>- **loadingStatus**: image loading status.<br>| | onComplete(callback: (event?: { width: number, height: number, componentWidth: number,<br> componentHeight: number, loadingStatus: number }) =&gt; void) | Triggered when an image is successfully loaded. The size of the loaded image is returned.<br>- **width**: width of the image, in pixels.<br>- **height**: height of the image, in pixels.<br>- **componentWidth**: width of the container component, in pixels.<br>- **componentHeight**: height of the container component, in pixels.<br>- **loadingStatus**: image loading status. |
| onError(callback: (event?: { componentWidth: number, componentHeight: number , message<sup>9+</sup>: string }) =&gt; void) | Triggered when an exception occurs during image loading.<br>- **componentWidth**: width of the container component, in pixels.<br>- **componentHeight**: height of the container component, in pixels.<br>| | onError(callback: (event?: { componentWidth: number, componentHeight: number , message<sup>9+</sup>: string }) =&gt; void) | Triggered when an exception occurs during image loading.<br>- **componentWidth**: width of the container component, in pixels.<br>- **componentHeight**: height of the container component, in pixels. |
| onFinish(event: () =&gt; void) | Triggered when the animation playback in the loaded SVG image is complete. If the animation is an infinite loop, this callback is not triggered.| | onFinish(event: () =&gt; void) | Triggered when the animation playback in the loaded SVG image is complete. If the animation is an infinite loop, this callback is not triggered. |
## Example ## Example
...@@ -215,7 +216,9 @@ struct Index { ...@@ -215,7 +216,9 @@ struct Index {
} }
``` ```
**NOTE**<br>For details about the request mode, timeout, and additional request parameters for loading online images, see [`request()`](../../reference/apis/js-apis-http.md) in the HTTP module. > **NOTE**
>
> For details about the request mode, timeout, and additional request parameters for loading online images, see [`request()`](../../reference/apis/js-apis-http.md) in the HTTP module.
### Setting Attributes ### Setting Attributes
...@@ -319,7 +322,7 @@ struct ImageExample3 { ...@@ -319,7 +322,7 @@ struct ImageExample3 {
.onError(() => { .onError(() => {
console.log('load image fail') console.log('load image fail')
}) })
.overlay('\nwidth: ' + String(this.width) + ' height: ' + String(this.height), { .overlay('\nwidth: ' + String(this.widthValue) + ' height: ' + String(this.heightValue), {
align: Alignment.Bottom, align: Alignment.Bottom,
offset: { x: 0, y: 20 } offset: { x: 0, y: 20 }
}) })
......
# PatternLock # PatternLock
The **\<PatternLock>** component allows users to use a pattern password for authentication. It enters the input state once being touched, and exits the input state and sends the entered password to the application once the finger leaves the screen. The **\<PatternLock>** component allows users to use a pattern password for authentication. It enters the input state once a finger is pressed against it, and exits the input state and completes the input once the finger leaves the screen.
> **NOTE** > **NOTE**
> >
...@@ -18,21 +18,21 @@ PatternLock(controller?: PatternLockController) ...@@ -18,21 +18,21 @@ PatternLock(controller?: PatternLockController)
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | | ---------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ |
| controller | [PatternLockController](#patternlockcontroller) | No | Controller of a component to reset the component status.<br>Default value: **null**| | controller | [PatternLockController](#patternlockcontroller) | No | Controller of a component to reset the component status. |
## Attributes ## Attributes
Except for **backgroundColor**, universal attributes are not supported. Except for **backgroundColor**, the universal attributes are not supported.
| Name | Type | Description | | Name | Type | Description |
| --------------- | ------------------------------------- | ------------------------------------------------------------ | | --------------- | ------------------------------------- | ------------------------------------------------------------ |
| sideLength | [Length](ts-types.md#length) | Width and height (same value) of the component. The minimum value is **0**.<br>Default value: **300vp**| | sideLength | [Length](ts-types.md#length) | Width and height (same value) of the component. If this attribute is set to 0 or a negative value, the component is not displayed.<br>Default value: **300vp**|
| circleRadius | [Length](ts-types.md#length) | Radius of the grid dot.<br>Default value: **14vp** | | circleRadius | [Length](ts-types.md#length) | Radius of the grid dot.<br>Default value: **14vp** |
| regularColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color of the grid dot in unselected state.<br>Default value: **Color.Black**| | regularColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color of the grid dot in unselected state.<br>Default value: **Color.Black**|
| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color of the grid dot in selected state.<br>Default value: **Color.Black**| | selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color of the grid dot in selected state.<br>Default value: **Color.Black**|
| activeColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color of the grid dot in active state.<br>Default value: **Color.Black**| | activeColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color of the grid dot in activated state, which is when the dot is highlighted but not selected.<br>Default value: **Color.Black**|
| pathColor | [ResourceColor](ts-types.md#resourcecolor) | Path color.<br>Default value: **Color.Blue** | | pathColor | [ResourceColor](ts-types.md#resourcecolor) | Path color.<br>Default value: **Color.Blue** |
| pathStrokeWidth | number \| string | Width of the path stroke. The minimum value is **0**.<br>Default value: **34vp** | | pathStrokeWidth | number \| string | Width of the path stroke. If this attribute is set to 0 or a negative value, the path stroke is not displayed.<br>Default value: **34vp** |
| autoReset | boolean | Whether to allow the user to reset the component status (that is, clear the input) by touching the component again after the input is complete. The value **true** means that the user can reset the component status by touching the component again after the input is complete, and **false** means the opposite.<br>Default value: **true**| | autoReset | boolean | Whether to allow the user to reset the component status (that is, clear the input) by touching the component again after the input is complete. The value **true** means that the user can reset the component status by touching the component again after the input is complete, and **false** means the opposite.<br>Default value: **true**|
## Events ## Events
...@@ -41,7 +41,7 @@ In addition to the [universal events](ts-universal-events-click.md), the followi ...@@ -41,7 +41,7 @@ In addition to the [universal events](ts-universal-events-click.md), the followi
| Name | Description | | Name | Description |
| ---------------------------------------- | ---------------------------------------- | | ---------------------------------------- | ---------------------------------------- |
| onPatternComplete(callback: (input: Array\<number\>) => void) | Invoked when the pattern password input is complete.<br>**input** is an array of digits that represent the connected dots in the pattern (0 to 8) and are arranged in the same sequence as the dots are connected.| | onPatternComplete(callback: (input: Array\<number\>) => void) | Invoked when the pattern password input is complete.<br>**input**: an array of digits that are the indexes of the connected grid dots and are arranged in the same sequence as the dots are connected. The indexes of the grid dots are as follows: 0 to 2 for the dots in the first row from left to right, 3–5 for the dots in the second row, and 6–8 for the dots in the third row.|
## PatternLockController ## PatternLockController
...@@ -67,36 +67,44 @@ Resets the component status. ...@@ -67,36 +67,44 @@ Resets the component status.
@Component @Component
struct PatternLockExample { struct PatternLockExample {
@State passwords: Number[] = [] @State passwords: Number[] = []
@State message: string = 'please input password' @State message: string = 'please input password!'
private patternLockController: PatternLockController = new PatternLockController() private patternLockController: PatternLockController = new PatternLockController()
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Column() {
Text(this.message).textAlign(TextAlign.Center) Text(this.message).textAlign(TextAlign.Center).margin(20).fontSize(20)
PatternLock(this.patternLockController) PatternLock(this.patternLockController)
.sideLength(150) .sideLength(200)
.circleRadius(7) .circleRadius(9)
.pathStrokeWidth(17) .pathStrokeWidth(18)
.backgroundColor(Color.White) .activeColor('#B0C4DE')
.selectedColor('#228B22')
.pathColor('#90EE90')
.backgroundColor('#F5F5F5')
.autoReset(true) .autoReset(true)
.onPatternComplete((input: Array<number>) => { .onPatternComplete((input: Array<number>) => {
if (input == null || input == undefined || input.length < 5) { // If the length of the entered password is less than 5, the system prompts the user to enter the password again.
this.message = 'The password length needs to be greater than 5.' if (input === null || input === undefined || input.length < 5) {
this.message = 'The password length needs to be greater than 5, please enter again.'
return return
} }
// Check whether the password length is greater than 0.
if (this.passwords.length > 0) { if (this.passwords.length > 0) {
if (this.passwords.toString() == input.toString()) { // Check whether the two passwords are the same. If yes, the system displays a message indicating that the password is set successfully. If no, the system prompts the user to enter the password again.
if (this.passwords.toString() === input.toString()) {
this.passwords = input this.passwords = input
this.message = 'Set password successfully: ' + this.passwords.toString() this.message = 'Set password successfully: ' + this.passwords.toString()
} else { } else {
this.message = 'Inconsistent passwords, please enter again.' this.message = 'Inconsistent passwords, please enter again.'
} }
} else { } else {
// The system prompts the user to enter the password again.
this.passwords = input this.passwords = input
this.message = "Please enter again." this.message = "Please enter again."
} }
}) })
Button('reset button').margin(30).onClick(() => { Button('Reset PatternLock').margin(30).onClick(() => {
// Reset the pattern lock.
this.patternLockController.reset() this.patternLockController.reset()
this.passwords = [] this.passwords = []
this.message = 'Please input password' this.message = 'Please input password'
......
# Search # Search
The **\<Search>** component provides an input area for users to search. The **\<Search>** component provides an area for users to enter search queries.
> **NOTE** > **NOTE**
> >
...@@ -21,7 +21,7 @@ Search(options?: { value?: string; placeholder?: string; icon?: string; controll ...@@ -21,7 +21,7 @@ Search(options?: { value?: string; placeholder?: string; icon?: string; controll
| value | string | No | Text input in the search text box. | | value | string | No | Text input in the search text box. |
| placeholder | string | No | Text displayed when there is no input. | | placeholder | string | No | Text displayed when there is no input. |
| icon | string | No | Path to the search icon. By default, the system search icon is used. The supported icon formats are .svg, .jpg, and .png.| | icon | string | No | Path to the search icon. By default, the system search icon is used. The supported icon formats are .svg, .jpg, and .png.|
| controller | SearchController | No | Controller. | | controller | SearchController | No | Controller of the **\<Search>** component. |
## Attributes ## Attributes
...@@ -31,24 +31,26 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -31,24 +31,26 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| ----------------------- | ------------------------------------------------ | ---------------------------------------------- | | ----------------------- | ------------------------------------------------ | ---------------------------------------------- |
| searchButton | string | Text on the search button located next to the search text box. By default, there is no search button. | | searchButton | string | Text on the search button located next to the search text box. By default, there is no search button. |
| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color. | | placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color. |
| placeholderFont | [Font](ts-types.md#font) | Placeholder text style. | | placeholderFont | [Font](ts-types.md#font) | Placeholder text font. |
| textFont | [Font](ts-types.md#font) | Text font for the search text box. | | textFont | [Font](ts-types.md#font) | Text font for the search text box. |
| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Text alignment mode in the search text box.<br>Default value: **TextAlign.Start** |
| copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed. | | copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed. |
| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Text alignment mode.<br>Default value: **TextAlign.Start**|
## Events ## Events
In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
| Name | Description | | Name | Description |
| ---------------------------------------- | ---------------------------------------- | | ------------------------------------------- | ------------------------------------------------------------ |
| onSubmit(callback: (value: string) => void) | Triggered when users click the search icon or the search button, or touch the search button on a soft keyboard.<br> -**value**: current text input.| | onSubmit(callback: (value: string) => void) | Invoked when users click the search icon or the search button, or touch the search button on a soft keyboard.<br> - **value**: current text input. |
| onChange(callback: (value: string) => void) | Triggered when the input in the text box changes.<br> -**value**: current text input. | | onChange(callback: (value: string) => void) | Invoked when the input in the text box changes.<br> - **value**: current text input. |
| onCopy(callback: (value: string) => void) | Triggered when data is copied to the pasteboard.<br> -**value**: text copied. | | onCopy(callback: (value: string) => void) | Invoked when data is copied to the pasteboard, which is displayed when the search text box is long pressed.<br> - **value**: text copied. |
| onCut(callback: (value: string) => void) | Triggered when data is cut from the pasteboard.<br> -**value**: text cut. | | onCut(callback: (value: string) => void) | Invoked when data is cut from the pasteboard, which is displayed when the search text box is long pressed.<br> - **value**: text cut. |
| onPaste(callback: (value: string) => void) | Triggered when data is pasted from the pasteboard.<br> -**value**: text pasted. | | onPaste(callback: (value: string) => void) | Invoked when data is pasted from the pasteboard, which is displayed when the search text box is long pressed.<br> -**value**: text pasted. |
## SearchController ## SearchController
Defines the controller of the **\<Search>** component. Implements the controller of the **\<Search>** component. Currently, the controller can be used to control the caret position.
### Objects to Import ### Objects to Import
``` ```
...@@ -78,25 +80,32 @@ struct SearchExample { ...@@ -78,25 +80,32 @@ struct SearchExample {
controller: SearchController = new SearchController() controller: SearchController = new SearchController()
build() { build() {
Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { Column() {
Text(this.submitValue) Text('onSubmit:' + this.submitValue).fontSize(18).margin(15)
Text(this.changeValue) Text('onChange:' + this.changeValue).fontSize(18).margin(15)
Search({value: this.changeValue, placeholder: 'Type to search', controller: this.controller}) Search({ value: this.changeValue, placeholder: 'Type to search...', controller: this.controller })
.searchButton('Search') .searchButton('SEARCH')
.width(400) .width(400)
.height(35) .height(40)
.backgroundColor(Color.White) .backgroundColor(Color.White)
.placeholderColor(Color.Grey) .placeholderColor(Color.Grey)
.placeholderFont({ size: 26, weight: 10, family: 'serif', style: FontStyle.Normal }) .placeholderFont({ size: 14, weight: 400 })
.textFont({ size: 14, weight: 400 })
.onSubmit((value: string) => { .onSubmit((value: string) => {
this.submitValue = value this.submitValue = value
}) })
.onChange((value: string) => { .onChange((value: string) => {
this.changeValue = value this.changeValue = value
}) })
.margin({ top: 30, left:10, right:10 }) .margin(20)
} Button('Set caretPosition 1')
.onClick(() => {
// Move the caret to after the first entered character.
this.controller.caretPosition(1)
})
}.width('100%')
} }
} }
``` ```
![search](figures/search.png)
![search](figures/search.gif)
...@@ -23,30 +23,30 @@ Slider(options?: {value?: number, min?: number, max?: number, step?: number, sty ...@@ -23,30 +23,30 @@ Slider(options?: {value?: number, min?: number, max?: number, step?: number, sty
| value | number | No| Current progress.<br>Default value: **0**| | value | number | No| Current progress.<br>Default value: **0**|
| min | number | No| Minimum value.<br>Default value: **0**| | min | number | No| Minimum value.<br>Default value: **0**|
| max | number | No| Maximum value.<br>Default value: **100**| | max | number | No| Maximum value.<br>Default value: **100**|
| step | number | No| Step of the slider. When the corresponding step is set, the slider slides intermittently.<br>Default value: **1**| | step | number | No| Step of the slider.<br>Default value: **1**|
| style | SliderStyle | No| Style of the slider.<br>Default value: **SliderStyle.OutSet**| | style | SliderStyle | No| Style of the slider thumb and track.<br>Default value: **SliderStyle.OutSet**|
| direction<sup>8+</sup> | [Axis](ts-appendix-enums.md#axis) | No| Whether the slider moves horizontally or vertically.<br>Default value: **Axis.Horizontal**| | direction<sup>8+</sup> | [Axis](ts-appendix-enums.md#axis) | No| Whether the slider moves horizontally or vertically.<br>Default value: **Axis.Horizontal**|
| reverse<sup>8+</sup> | boolean | No| Whether the slider values are reversed.<br>Default value: **false**| | reverse<sup>8+</sup> | boolean | No| Whether the slider values are reversed. By default, the values increase from left to right for a horizontal slider and from top to bottom for a vertical slider.<br>Default value: **false**|
## SliderStyle ## SliderStyle
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| OutSet | The slider is on the slider rail.| | OutSet | The slider is on the slider track.|
| InSet | The slider is in the slider rail.| | InSet | The slider is in the slider track.|
## Attributes ## Attributes
Touch target configuration is not supported. Except touch target attributes, the universal attributes are supported.
| Name| Type| Description| | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| blockColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the slider.| | blockColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the slider.|
| trackColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the slider.| | trackColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the slider.|
| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the slider rail that has been slid.| | selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the selected part of the slider track.|
| showSteps | boolean | Whether to display the current step.<br>Default value: **false**| | showSteps | boolean | Whether to display the current step.<br>Default value: **false**|
| showTips | boolean | Whether to display a bubble to indicate the percentage when sliding.<br>Default value: **false**| | showTips | boolean | Whether to display a bubble to indicate the percentage when the user drags the slider.<br>Default value: **false** |
| trackThickness | [Length](ts-types.md#length) | Track thickness of the slider.| | trackThickness | [Length](ts-types.md#length) | Track thickness of the slider.|
...@@ -56,7 +56,7 @@ In addition to the **OnAppear** and **OnDisAppear** universal events, the follow ...@@ -56,7 +56,7 @@ In addition to the **OnAppear** and **OnDisAppear** universal events, the follow
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onChange(callback: (value: number, mode: SliderChangeMode) =&gt; void) | Invoked when the slider slides.<br>**value**: current progress.<br>**mode**: dragging state.| | onChange(callback: (value: number, mode: SliderChangeMode) =&gt; void) | Invoked when the slider slides.<br>**value**: current slider value. If the return value contains decimals, you can use **Math.toFixed()** to process the data to the desired precision.<br>**mode**: dragging state.|
## SliderChangeMode ## SliderChangeMode
...@@ -65,7 +65,7 @@ In addition to the **OnAppear** and **OnDisAppear** universal events, the follow ...@@ -65,7 +65,7 @@ In addition to the **OnAppear** and **OnDisAppear** universal events, the follow
| Begin | 0 | The user starts to drag the slider.| | Begin | 0 | The user starts to drag the slider.|
| Moving | 1 | The user is dragging the slider.| | Moving | 1 | The user is dragging the slider.|
| End | 2 | The user stops dragging the slider.| | End | 2 | The user stops dragging the slider.|
| Click | 3 | The user moves the slider by touching the slider rail.| | Click | 3 | The user moves the slider by touching the slider track.|
## Example ## Example
...@@ -75,105 +75,150 @@ In addition to the **OnAppear** and **OnDisAppear** universal events, the follow ...@@ -75,105 +75,150 @@ In addition to the **OnAppear** and **OnDisAppear** universal events, the follow
@Entry @Entry
@Component @Component
struct SliderExample { struct SliderExample {
@State outSetValue: number = 40 @State outSetValueOne: number = 40
@State inSetValue: number = 40 @State inSetValueOne: number = 40
@State outVerticalSetValue: number = 40 @State outSetValueTwo: number = 40
@State inVerticalSetValue: number = 40 @State inSetValueTwo: number = 40
@State vOutSetValueOne: number = 40
@State vInSetValueOne: number = 40
@State vOutSetValueTwo: number = 40
@State vInSetValueTwo: number = 40
build() { build() {
Column({ space: 5 }) { Column({ space: 8 }) {
Text('slider out set').fontSize(9).fontColor(0xCCCCCC).width('90%') Text('outset slider').fontSize(9).fontColor(0xCCCCCC).width('90%').margin(15)
Row() { Row() {
Slider({ Slider({
value: this.outSetValue, value: this.outSetValueOne,
min: 0, min: 0,
max: 100, max: 100,
step: 1,
style: SliderStyle.OutSet style: SliderStyle.OutSet
}) })
.blockColor(Color.Blue)
.trackColor(Color.Gray)
.selectedColor(Color.Blue)
.showSteps(true)
.showTips(true) .showTips(true)
.onChange((value: number, mode: SliderChangeMode) => { .onChange((value: number, mode: SliderChangeMode) => {
this.outSetValue = value this.outSetValueOne = value
console.info('value:' + value + 'mode:' + mode.toString()) console.info('value:' + value + 'mode:' + mode.toString())
}) })
Text(this.outSetValue.toFixed(0)).fontSize(16) // toFixed(0) converts the return value of the slider to an integer.
Text(this.outSetValueOne.toFixed(0)).fontSize(12)
}
.width('80%')
Row() {
Slider({
value: this.outSetValueTwo,
step: 10,
style: SliderStyle.OutSet
})
.showSteps(true)
.onChange((value: number, mode: SliderChangeMode) => {
this.outSetValueTwo = value
console.info('value:' + value + 'mode:' + mode.toString())
})
Text(this.outSetValueTwo.toFixed(0)).fontSize(12)
} }
.padding({ top: 50 })
.width('80%') .width('80%')
Text('slider in set').fontSize(9).fontColor(0xCCCCCC).width('90%') Text('inset slider').fontSize(9).fontColor(0xCCCCCC).width('90%').margin(15)
Row() { Row() {
Slider({ Slider({
value: this.inSetValue, value: this.inSetValueOne,
min: 0, min: 0,
max: 100, max: 100,
step: 1,
style: SliderStyle.InSet style: SliderStyle.InSet
}) })
.blockColor(0xCCCCCC) .blockColor('#191970')
.trackColor(Color.Black) .trackColor('#ADD8E6')
.selectedColor(0xCCCCCC) .selectedColor('#4169E1')
.showSteps(false) .showTips(true)
.showTips(false)
.onChange((value: number, mode: SliderChangeMode) => { .onChange((value: number, mode: SliderChangeMode) => {
this.inSetValue = value this.inSetValueOne = value
console.info('value:' + value + 'mode:' + mode.toString()) console.info('value:' + value + 'mode:' + mode.toString())
}) })
Text(this.inSetValue.toFixed(0)).fontSize(16) Text(this.inSetValueOne.toFixed(0)).fontSize(12)
}
.width('80%')
Row() {
Slider({
value: this.inSetValueTwo,
step: 10,
style: SliderStyle.InSet
})
.blockColor('#191970')
.trackColor('#ADD8E6')
.selectedColor('#4169E1')
.showSteps(true)
.onChange((value: number, mode: SliderChangeMode) => {
this.inSetValueTwo = value
console.info('value:' + value + 'mode:' + mode.toString())
})
Text(this.inSetValueTwo.toFixed(0)).fontSize(12)
} }
.width('80%') .width('80%')
Row() { Row() {
Column() { Column() {
Text('slider out direction set').fontSize(9).fontColor(0xCCCCCC).width('50%') Text('vertical outset slider').fontSize(9).fontColor(0xCCCCCC).width('50%').margin(15)
Row() {
Slider({ Slider({
value: this.outVerticalSetValue, value: this.vOutSetValueOne,
min: 0,
max: 100,
step: 1,
style: SliderStyle.OutSet, style: SliderStyle.OutSet,
direction: Axis.Vertical direction: Axis.Vertical
}) })
.blockColor(Color.Blue) .blockColor('#191970')
.trackColor(Color.Gray) .trackColor('#ADD8E6')
.selectedColor(Color.Blue) .selectedColor('#4169E1')
.showSteps(true)
.showTips(true) .showTips(true)
.onChange((value: number, mode: SliderChangeMode) => { .onChange((value: number, mode: SliderChangeMode) => {
this.outVerticalSetValue = value this.vOutSetValueOne = value
console.info('value:' + value + 'mode:' + mode.toString())
})
Slider({
value: this.vOutSetValueTwo,
step: 10,
style: SliderStyle.OutSet,
direction: Axis.Vertical
})
.blockColor('#191970')
.trackColor('#ADD8E6')
.selectedColor('#4169E1')
.showSteps(true)
.onChange((value: number, mode: SliderChangeMode) => {
this.vOutSetValueTwo = value
console.info('value:' + value + 'mode:' + mode.toString()) console.info('value:' + value + 'mode:' + mode.toString())
}) })
Text(this.outVerticalSetValue.toFixed(0)).fontSize(16) }
}.width('50%').height(300) }.width('50%').height(300)
Column() { Column() {
Text('slider in direction set').fontSize(9).fontColor(0xCCCCCC).width('50%') Text('vertical inset slider').fontSize(9).fontColor(0xCCCCCC).width('50%').margin(15)
Row() {
Slider({ Slider({
value: this.inVerticalSetValue, value: this.vInSetValueOne,
min: 0,
max: 100,
step: 1,
style: SliderStyle.InSet, style: SliderStyle.InSet,
direction: Axis.Vertical direction: Axis.Vertical,
reverse: true // By default, at the top of the vertical slider is the min value and at the bottom is the max value. Therefore, if you want to slide from bottom to top, set reverse to true.
})
.showTips(true)
.onChange((value: number, mode: SliderChangeMode) => {
this.vInSetValueOne = value
console.info('value:' + value + 'mode:' + mode.toString())
}) })
.blockColor(0xCCCCCC) Slider({
.trackColor(Color.Black) value: this.vInSetValueTwo,
.selectedColor(0xCCCCCC) step: 10,
.showSteps(false) style: SliderStyle.InSet,
.showTips(false) direction: Axis.Vertical,
reverse: true
})
.showSteps(true)
.onChange((value: number, mode: SliderChangeMode) => { .onChange((value: number, mode: SliderChangeMode) => {
this.inVerticalSetValue = value this.vInSetValueTwo = value
console.info('value:' + value + 'mode:' + mode.toString()) console.info('value:' + value + 'mode:' + mode.toString())
}) })
Text(this.inVerticalSetValue.toFixed(0)).fontSize(16) }
}.width('50%').height(300) }.width('50%').height(300)
} }
}.width('100%')
}.width('100%').margin({ top: 5 })
} }
} }
``` ```
......
...@@ -17,10 +17,12 @@ Only the child component **\<[StepperItem](ts-basic-components-stepperitem.md)>* ...@@ -17,10 +17,12 @@ Only the child component **\<[StepperItem](ts-basic-components-stepperitem.md)>*
Stepper(value?: { index?: number }) Stepper(value?: { index?: number })
**Parameters** **Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | Name| Type| Mandatory | Description|
| index | number | No| Index of the **\<StepperItem>** that is currently displayed.<br>Default value: **0** | | ------| -------- | --------------- | -------- |
| index | number | No| Index of the **\<StepperItem>** that is currently displayed.<br>Default value: **0**|
## Attributes ## Attributes
...@@ -32,11 +34,11 @@ None ...@@ -32,11 +34,11 @@ None
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onFinish(callback: () =&gt; void) | Invoked when the **nextLabel** of the last **\<StepperItem>** in the **\<Stepper>** is clicked. | | onFinish(callback: () =&gt; void) | Invoked when the **nextLabel** of the last **\<StepperItem>** in the **\<Stepper>** is clicked.|
| onSkip(callback: () =&gt; void) | Invoked when the current **\<StepperItem>** is **ItemState.Skip** and the **nextLabel** is clicked. | | onSkip(callback: () =&gt; void) | Invoked when the current **\<StepperItem>** is **ItemState.Skip** and the **nextLabel** is clicked.|
| onChange(callback: (prevIndex?: number, index?: number) =&gt; void) | Invoked when the text button on the left or right is clicked to switch between steps.<br>- **prevIndex**: index of the step page before the switching.<br>- **index**: index of the step page after the switching, that is, index of the previous or next page. | | onChange(callback: (prevIndex?: number, index?: number) =&gt; void) | Invoked when the user switches to the previous or next step.<br>- **prevIndex**: index of the step page before the switching.<br>- **index**: index of the step page after the switching, that is, index of the previous or next page.|
| onNext(callback: (index?: number, pendingIndex?: number) =&gt; void) | Invoked when a user switches to the next step.<br>- **index**: index of the current step page.<br>- **pendingIndex**: index of the next page. | | onNext(callback: (index?: number, pendingIndex?: number) =&gt; void) | Invoked when a user switches to the next step.<br>- **index**: index of the current step page.<br>- **pendingIndex**: index of the next page.|
| onPrevious(callback: (index?: number, pendingIndex?: number) =&gt; void) | Invoked when a user switches to the previous step.<br>- **index**: index of the current step page.<br>- **pendingIndex**: index of the previous page. | | onPrevious(callback: (index?: number, pendingIndex?: number) =&gt; void) | Invoked when a user switches to the previous step.<br>- **index**: index of the current step page.<br>- **pendingIndex**: index of the previous page.|
## Example ## Example
...@@ -49,73 +51,83 @@ struct StepperExample { ...@@ -49,73 +51,83 @@ struct StepperExample {
@State currentIndex: number = 0 @State currentIndex: number = 0
@State firstState: ItemState = ItemState.Normal @State firstState: ItemState = ItemState.Normal
@State secondState: ItemState = ItemState.Normal @State secondState: ItemState = ItemState.Normal
@State thirdState: ItemState = ItemState.Normal
build() { build() {
Stepper({ Stepper({
index: this.currentIndex index: this.currentIndex
}) { }) {
// First step page
StepperItem() { StepperItem() {
Column() {
Text('Page One') Text('Page One')
.fontSize(35) .fontSize(35)
.fontColor(Color.Blue) .fontColor(Color.Blue)
.width(200)
.lineHeight(50) .lineHeight(50)
.margin({ top: 250 }) .margin({ top: 250, bottom: 50 })
Button('change status:' + this.firstState)
.onClick(() => {
this.firstState = this.firstState === ItemState.Skip ? ItemState.Normal : ItemState.Skip
})
}.width('100%')
} }
.nextLabel('') .nextLabel('Next')
.position({ x: '35%', y: 0 }) .status(this.firstState)
// Second step page
StepperItem() { StepperItem() {
Column() {
Text('Page Two') Text('Page Two')
.fontSize(35) .fontSize(35)
.fontColor(Color.Blue) .fontColor(Color.Blue)
.width(200)
.lineHeight(50) .lineHeight(50)
.margin({ top: 250 }) .margin({ top: 250, bottom: 50 })
Button('change status:' + this.secondState)
.onClick(() => { .onClick(() => {
this.firstState = this.firstState === ItemState.Skip ? ItemState.Normal : ItemState.Skip this.secondState = this.secondState === ItemState.Disabled ? ItemState.Normal : ItemState.Disabled
}) })
}.width('100%')
} }
.nextLabel('Next') .nextLabel('Next')
.prevLabel('Previous') .prevLabel('Previous')
.status(this.firstState) .status(this.secondState)
.position({ x: '35%', y: 0 }) // Third step page
StepperItem() { StepperItem() {
Column() {
Text('Page Three') Text('Page Three')
.fontSize(35) .fontSize(35)
.fontColor(Color.Blue) .fontColor(Color.Blue)
.width(200)
.lineHeight(50) .lineHeight(50)
.margin({ top: 250 }) .margin({ top: 250, bottom: 50 })
Button('change status:' + this.thirdState)
.onClick(() => { .onClick(() => {
this.secondState = this.secondState === ItemState.Waiting ? ItemState.Normal : ItemState.Waiting this.thirdState = this.thirdState === ItemState.Waiting ? ItemState.Normal : ItemState.Waiting
}) })
}.width('100%')
} }
.position({ x: '35%', y: 0 }) .status(this.thirdState)
.status(this.secondState) // Fourth step page
StepperItem() { StepperItem() {
Text('Page four') Text('Page four')
.fontSize(35) .fontSize(35)
.fontColor(Color.Blue) .fontColor(Color.Blue)
.width(200) .width('100%')
.textAlign(TextAlign.Center)
.lineHeight(50) .lineHeight(50)
.margin({ top: 250 }) .margin({ top: 250 })
} }
.position({ x: '35%', y: 0 })
.nextLabel('Finish') .nextLabel('Finish')
} }
.onFinish(() => { .onFinish(() => {
console.log('onFinish') // Define the processing logic for when Finish on the last page is clicked, for example, redirection.
console.info('onFinish')
}) })
.onSkip(() => { .onSkip(() => {
console.log('onSkip') // Define the processing logic for when Skip on the page is clicked, for example, dynamically changing the index of the <Stepper> to redirect to a specific step.
console.info('onSkip')
}) })
.onChange((prevIndex: number, index: number) => { .onChange((prevIndex: number, index: number) => {
this.currentIndex = index this.currentIndex = index
}) })
.align(Alignment.Center)
} }
} }
``` ```
......
...@@ -22,18 +22,18 @@ StepperItem() ...@@ -22,18 +22,18 @@ StepperItem()
| Name| Type| Description| | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| prevLabel | string | When the **\<Stepper>** contains more than one page, the default value for all pages except the first page is **Back**.| | prevLabel | string | Text label of the button on the left. When the **\<Stepper>** contains more than one page, the default value for all pages except the first page is **Back**.|
| nextLabel | string | When the stepper contains more than one page, the default value for the last page is **Start**, and the default value for other pages is **Next**.| | nextLabel | string | Text label of the button on the right. The default value is **Start** for the last page and **Next** for the other pages.|
| status | ItemState | Status of the **\<StepperItem>**.<br>Default value: **ItemState.Normal**| | status | ItemState | Display status of **nextLabel** in the stepper.<br>Default value: **ItemState.Normal**|
## ItemState ## ItemState
| Name| Description| | Name | Value | Description|
| -------- | -------- | | -------- | -------- |-------- |
| Normal | The right button is clickable and can navigate users to the next **\<StepperItem>** when it is clicked.| | Normal | 0 |The button on the right is clickable and can navigate users to the next **\<StepperItem>** when it is clicked.|
| Disabled | The right button is grayed out and unavailable.| | Disabled | 1 |The button on the right is grayed out and unavailable.|
| Waiting | The right button is not displayed, and a progress bar is displayed instead.| | Waiting | 2 | The button on the right is not displayed, and a progress bar is displayed instead.|
| Skip | The current **\<StepperItem>** is skipped, and the next **\<StepperItem>** is displayed.| | Skip | 3 |The button on the right reads "Skip". You can define the processing logic for this state in the **onSkip** callback of the stepper.|
## Example ## Example
......
# TextArea # TextArea
The **\<TextArea>** component provides multi-line text input and responds to certain input events. The **\<TextArea>** component provides multi-line text input and automatically wraps text so that each line does not have more than the width of the component.
> **NOTE** > **NOTE**
> >
...@@ -20,7 +20,7 @@ TextArea(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Tex ...@@ -20,7 +20,7 @@ TextArea(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Tex
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----------------------- | ---------------------------------------- | ---- | -------------- | | ----------------------- | ---------------------------------------- | ---- | -------------- |
| placeholder | [ResourceStr](ts-types.md#resourcestr) | No | Text displayed when there is no input. | | placeholder | [ResourceStr](ts-types.md#resourcestr) | No | Placeholder text displayed when there is no input. |
| text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input. | | text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input. |
| controller<sup>8+</sup> | [TextAreaController](#textareacontroller8) | No | Text area controller.| | controller<sup>8+</sup> | [TextAreaController](#textareacontroller8) | No | Text area controller.|
...@@ -35,23 +35,24 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -35,23 +35,24 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| placeholderFont | [Font](ts-types.md#font) | Placeholder text style. | | placeholderFont | [Font](ts-types.md#font) | Placeholder text style. |
| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment of the text.<br>Default value: **TextAlign.Start**| | textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment of the text.<br>Default value: **TextAlign.Start**|
| caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box. | | caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box. |
| inputFilter<sup>8+</sup> | {<br>value: [ResourceStr](ts-types.md#resourcestr),<br>error?: (value: string) => void<br>} | 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.<br>- **value**: regular expression to set.<br>- **error**: ignored content to return when regular expression matching fails.| | inputFilter<sup>8+</sup> | {<br>value: [ResourceStr](ts-types.md#resourcestr),<br>error?: (value: string) => void<br>} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The specified regular expression can match single characters, but not strings.<br>- **value**: regular expression to set.<br>- **error**: filtered-out content to return when regular expression matching fails.|
| copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.| | copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.|
## Events ## Events
In addition to the [universal events](ts-universal-events-click.md), the following events are supported. In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
| Name | Description | | Name | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| onChange(callback: (value: string) =&gt; void) | Triggered when the input changes. | | onChange(callback: (value: string) =&gt; void) | Triggered when the input in the text box changes.<br>- **value**: text entered. |
| onCopy<sup>8+</sup>(callback:(value: string) =&gt; void) | Triggered when the copy button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>- **value**: text to be copied.| | onCopy<sup>8+</sup>(callback:(value: string) =&gt; void) | Triggered when the copy button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>- **value**: text to be copied.|
| onCut<sup>8+</sup>(callback:(value: string) =&gt; void) | Triggered when the cut button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>- **value**: text to be cut.| | onCut<sup>8+</sup>(callback:(value: string) =&gt; void) | Triggered when the cut button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>- **value**: text to be cut.|
| onPaste<sup>8+</sup>(callback:(value: string) =&gt; void) | Triggered when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>- **value**: text to be pasted.| | onPaste<sup>8+</sup>(callback:(value: string) =&gt; void) | Triggered when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>- **value**: text to be pasted.|
## TextAreaController<sup>8+</sup> ## TextAreaController<sup>8+</sup>
Defines the controller for controlling the **\<TextArea>** component. Defines the controller for controlling the **\<TextArea>** component. Currently, the controller can be used to control the caret position.
### Objects to Import ### Objects to Import
...@@ -74,63 +75,35 @@ Sets the position of the caret. ...@@ -74,63 +75,35 @@ Sets the position of the caret.
## Example ## Example
### Multi-line Text Input
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct TextAreaExample1 { struct TextAreaExample {
controller: TextAreaController = new TextAreaController()
@State text: string = '' @State text: string = ''
controller: TextAreaController = new TextAreaController()
build() { build() {
Column() { Column() {
TextArea({ placeholder: 'input your word', controller: this.controller}) TextArea({ placeholder: 'The text area can hold an unlimited amount of text. input your word', controller: this.controller })
.placeholderColor("rgb(0,0,225)") .placeholderFont({ size: 14, weight: 400 })
.placeholderFont({ size: 30, weight: 100, family: 'cursive', style: FontStyle.Italic }) .width(400)
.textAlign(TextAlign.Center)
.caretColor(Color.Blue)
.height(50) .height(50)
.fontSize(30) .margin(20)
.fontWeight(FontWeight.Bold) .fontSize(14)
.fontFamily("sans-serif")
.fontStyle(FontStyle.Normal)
.fontColor(Color.Red)
.inputFilter('^[\u4E00-\u9FA5A-Za-z0-9_]+$',(value: string) => {
console.info("hyb"+value)
})
.onChange((value: string) => { .onChange((value: string) => {
this.text = value this.text = value
this.controller.caretPosition(-1)
}) })
Text(this.text).width('90%') Text(this.text)
} Button('Set caretPosition 1')
} .margin(15)
}
```
![en-us_image_0000001256858399](figures/en-us_image_0000001256858399.gif)
### Setting the Caret
```ts
// xxx.ets
@Entry
@Component
struct TextAreaExample2 {
controller: TextAreaController = new TextAreaController()
build() {
Column() {
TextArea({ placeholder: 'input your word',controller:this.controller })
Button('caretPosition')
.onClick(() => { .onClick(() => {
this.controller.caretPosition(4) // Move the caret to after the first entered character.
this.controller.caretPosition(1)
}) })
} }.width('100%')
} }
} }
``` ```
![en-us_image_0000001212058476](figures/en-us_image_0000001212058476.png) ![textArea](figures/textArea.gif)
# TextInput # TextInput
The **\<TextInput>** component provides single-line text input and is able to respond to input events. The **\<TextInput>** component provides single-line text input.
> **NOTE** > **NOTE**
> >
...@@ -20,28 +20,28 @@ TextInput(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Te ...@@ -20,28 +20,28 @@ TextInput(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Te
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----------------------- | ---------------------------------------- | ---- | --------------- | | ----------------------- | ---------------------------------------- | ---- | --------------- |
| placeholder | [ResourceStr](ts-types.md#resourcestr) | No | Text displayed when there is no input. | | placeholder | [ResourceStr](ts-types.md#resourcestr) | No | Placeholder text displayed when there is no input. |
| text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input. | | text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input. |
| controller<sup>8+</sup> | [TextInputController](#textinputcontroller8) | No | Text input controller.| | controller<sup>8+</sup> | [TextInputController](#textinputcontroller8) | No | Text input controller.|
## Attributes ## Attributes
In addition to the universal attributes and [text style](ts-universal-attributes-text-style.md) attributes, the following attributes are supported. In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name | Type | Description | | Name | Type | Description |
| ------------------------ | ---------------------------------------- | ---------------------------------------- | | ------------------------ | ---------------------------------------- | ---------------------------------------- |
| type | InputType | Input box type.<br>Default value: **InputType.Normal** | | type | InputType | Input box type.<br>Default value: **InputType.Normal** |
| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color.| | placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color.|
| placeholderFont | [Font](ts-types.md#font) | Placeholder text style.| | placeholderFont | [Font](ts-types.md#font) | Placeholder text font.|
| enterKeyType | EnterKeyType | How the Enter key is labeled.<br>Default value: **EnterKeyType.Done** | | enterKeyType | EnterKeyType | Type of the Enter key. Currently, only the default value is supported.<br>Default value: **EnterKeyType.Done**|
| caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box. | | caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box. |
| maxLength | number | Maximum number of characters in the text input. | | maxLength | number | Maximum number of characters in the text input. |
| inputFilter<sup>8+</sup> | {<br>value: [ResourceStr](ts-types.md#resourcestr),<br>error?: (value: string) =&gt; void<br>} | 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.<br>- **value**: regular expression to set.<br>- **error**: ignored content to return when regular expression matching fails.| | inputFilter<sup>8+</sup> | {<br>value: [ResourceStr](ts-types.md#resourcestr),<br>error?: (value: string) =&gt; void<br>} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The specified regular expression can match single characters, but not strings.<br>- **value**: regular expression to set.<br>- **error**: filtered-out content to return when regular expression matching fails.|
| copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.| | copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.|
| showPasswordIcon<sup>9+</sup> | boolean | Whether to display the show password icon at the end of the password text box.<br>Default value: **true**| | showPasswordIcon<sup>9+</sup> | boolean | Whether to display the show password icon at the end of the password text box.<br>Default value: **true**|
| style<sup>9+</sup> | TextInputStyle | Text input style.<br>Default value: **TextInputStyle.Default**| | style<sup>9+</sup> | TextInputStyle | Text input style.<br>Default value: **TextInputStyle.Default**|
| textAlign<sup>9+</sup> | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment mode of the text.<br>Default value: **TextAlign.Start** | | textAlign<sup>9+</sup> | [TextAlign](ts-appendix-enums.md#textalign) | Alignment mode of the text in the text box.<br>Default value: **TextAlign.Start** |
## EnterKeyType ## EnterKeyType
...@@ -63,24 +63,26 @@ In addition to the universal attributes and [text style](ts-universal-attributes ...@@ -63,24 +63,26 @@ In addition to the universal attributes and [text style](ts-universal-attributes
| Number | Digit input mode. | | Number | Digit input mode. |
| PhoneNumber<sup>9+</sup> | Phone number input mode.<br>The value can contain digits, plus signs (+), hyphens (-), asterisks (*), and number signs (#). The length is not limited.| | PhoneNumber<sup>9+</sup> | Phone number input mode.<br>The value can contain digits, plus signs (+), hyphens (-), asterisks (*), and number signs (#). The length is not limited.|
## SwipeEdgeEffect<sup>9+</sup> ## TextInputStyle<sup>9+</sup>
| Name | Description | | Name | Description |
| ------------------ | ------------- | | ------------------ | ------------- |
| Default | Default style. The caret width is fixed at 1.5 vp, and the caret height increases with the font size. | | Default | Default style. The caret width is fixed at 1.5 vp, and the caret height is subject to the background height and font size of the selected text. |
| Inline | Inline input style. When text is selected, its background height is the same as the height of the text box. | | Inline | Inline input style. The background height of the selected text is the same as the height of the text box. |
## Event ## Event
In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
| Name | Description | | Name | Description |
| ---------------------------------------- | ---------------------------------------- | | ---------------------------------------- | ---------------------------------------- |
| onChange(callback: (value: string) =&gt; void) | Triggered when the input changes. | | onChange(callback: (value: string) =&gt; void) | Triggered when the input changes. |
| onSubmit(callback: (enterKey: EnterKeyType) =&gt; void) | Triggered when the Enter key on the physical or soft keyboard is pressed. | | onSubmit(callback: (enterKey: EnterKeyType) =&gt; void) | Triggered when the Enter key on the keyboard is pressed. The return value is the current type of the Enter key. |
| onEditChanged(callback: (isEditing: boolean) =&gt; void)<sup>(deprecated) </sup> | Triggered when the input status changes. | | onEditChanged(callback: (isEditing: boolean) =&gt; void)<sup>(deprecated)</sup> | Triggered when the input status changes. Sicne API version 8, **onEditChange** is recommended. |
| onEditChange(callback: (isEditing: boolean) =&gt; void) <sup>8+</sup> | Triggered when the input status changes. | | onEditChange(callback: (isEditing: boolean) =&gt; void)<sup>8+</sup> | Triggered when the input status changes. If the value of **isEditing** is **true**, text input is in progress. |
| onCopy<sup>8+</sup>(callback:(value: string) =&gt; void) | Triggered when the copy button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be copied.| | onCopy(callback:(value: string) =&gt; void)<sup>8+</sup> | Triggered when the copy button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be copied.|
| onCut<sup>8+</sup>(callback:(value: string) =&gt; void) | Triggered when the cut button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be cut.| | onCut(callback:(value: string) =&gt; void)<sup>8+</sup> | Triggered when the cut button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be cut.|
| onPaste<sup>8+</sup>(callback:(value: string) =&gt; void) | Triggered when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be pasted.| | onPaste(callback:(value: string) =&gt; void)<sup>8+</sup> | Triggered when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be pasted.|
## TextInputController<sup>8+</sup> ## TextInputController<sup>8+</sup>
...@@ -105,60 +107,53 @@ Sets the position of the caret. ...@@ -105,60 +107,53 @@ Sets the position of the caret.
## Example ## Example
### Single-line Text Input
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct TextInputExample1 { struct TextInputExample {
@State text: string = '' @State text: string = ''
controller: TextInputController = new TextInputController()
build() { build() {
Column() { Column() {
TextInput({ placeholder: 'input your word' }) TextInput({ placeholder: 'input your word...', controller: this.controller })
.placeholderColor("rgb(0,0,225)") .placeholderColor(Color.Grey)
.placeholderFont({ size: 30, weight: 100, family: 'cursive', style: FontStyle.Italic }) .placeholderFont({ size: 14, weight: 400 })
.caretColor(Color.Blue) .caretColor(Color.Blue)
.height(50) .width(400)
.fontSize(30) .height(40)
.fontWeight(FontWeight.Bold) .margin(20)
.fontFamily("sans-serif") .fontSize(14)
.fontStyle(FontStyle.Normal) .fontColor(Color.Black)
.fontColor(Color.Red)
.onChange((value: string) => { .onChange((value: string) => {
this.text = value this.text = value
}) })
Text(this.text).width('90%') Text(this.text)
} Button('Set caretPosition 1')
} .margin(15)
}
```
![en-us_image_0000001212378402](figures/en-us_image_0000001212378402.gif)
### Setting the Caret
```ts
// xxx.ets
@Entry
@Component
struct TextInputExample2 {
@State text: string = ''
controller: TextInputController = new TextInputController()
build() {
Column() {
TextInput({ placeholder: 'Please input your words.', controller:this.controller})
Button('caretPosition')
.onClick(() => { .onClick(() => {
this.controller.caretPosition(4) // Move the caret to after the first entered character.
this.controller.caretPosition(1)
}) })
} // Password text box.
TextInput({ placeholder: 'input your password...' })
.width(400)
.height(40)
.margin(20)
.type(InputType.Password)
.maxLength(9)
.showPasswordIcon(true)
// Inline-style text box.
TextInput({ placeholder: 'inline style' })
.width(400)
.height(50)
.margin(20)
.borderRadius(0)
.style(TextInputStyle.Inline)
}.width('100%')
} }
} }
``` ```
![en-us_image_0000001212058468](figures/en-us_image_0000001212058468.png) ![textInput](figures/textInput.gif)
# Web # Web
The **<Web\>** component can be used to display web pages.
> **NOTE** > **NOTE**
> >
> - This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > - This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
> - You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer. > - You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer.
The **<Web\>** component can be used to display web pages.
## Required Permissions ## Required Permissions
To use online resources, the application must have the **ohos.permission.INTERNET** permission. For details about how to apply for a permission, see [Declaring Permissions](../../security/accesstoken-guidelines.md). To use online resources, the application must have the **ohos.permission.INTERNET** permission. For details about how to apply for a permission, see [Declaring Permissions](../../security/accesstoken-guidelines.md).
...@@ -16,7 +16,7 @@ Not supported ...@@ -16,7 +16,7 @@ Not supported
## APIs ## APIs
Web(options: { src: ResourceStr, controller: WebController }) Web(options: { src: ResourceStr, controller: WebController | WebviewController})
> **NOTE** > **NOTE**
> >
...@@ -27,17 +27,32 @@ Web(options: { src: ResourceStr, controller: WebController }) ...@@ -27,17 +27,32 @@ Web(options: { src: ResourceStr, controller: WebController })
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------- | ------------------------------- | ---- | ------- | | ---------- | ------------------------------- | ---- | ------- |
| src | [ResourceStr](ts-types.md) | Yes | Address of a web page resource.| | src | [ResourceStr](ts-types.md) | Yes | Address of a web page resource.|
| controller | [WebController](#webcontroller) | No | Controller. | | controller | [WebController](#webcontroller) or WebviewController |Yes | Controller. |
**Example** **Example**
Loading Online Web Pages Example of loading online web pages:
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -46,13 +61,13 @@ Web(options: { src: ResourceStr, controller: WebController }) ...@@ -46,13 +61,13 @@ Web(options: { src: ResourceStr, controller: WebController })
} }
``` ```
Loading Local Web Pages Example of loading local web pages:
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: $rawfile("index.html"), controller: this.controller }) Web({ src: $rawfile("index.html"), controller: this.controller })
...@@ -94,7 +109,7 @@ Sets whether to enable the DOM Storage API. By default, this feature is disabled ...@@ -94,7 +109,7 @@ Sets whether to enable the DOM Storage API. By default, this feature is disabled
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -108,13 +123,13 @@ Sets whether to enable the DOM Storage API. By default, this feature is disabled ...@@ -108,13 +123,13 @@ Sets whether to enable the DOM Storage API. By default, this feature is disabled
fileAccess(fileAccess: boolean) fileAccess(fileAccess: boolean)
Sets whether to enable the access to the file system in the application. By default, this feature is disabled. Access to the files specified through [$rawfile(filepath/filename)](../../ui/ts-resource-access.md) are not affected by this attribute. Sets whether to enable access to the file system in the application. Access to the files in **rawfile** specified through [$rawfile(filepath/filename)](../../quick-start/resource-categories-and-access.md) are not affected by the setting.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ---------- | ------- | ---- | ---- | ---------------------------------------- | | ---------- | ------- | ---- | ---- | ---------------------------------------- |
| fileAccess | boolean | Yes | true | Whether to enable the access to the file system in the application.| | fileAccess | boolean | Yes | true | Whether to enable access to the file system in the application. By default, this feature is enabled.|
**Example** **Example**
...@@ -123,7 +138,7 @@ Sets whether to enable the access to the file system in the application. By defa ...@@ -123,7 +138,7 @@ Sets whether to enable the access to the file system in the application. By defa
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -137,7 +152,7 @@ Sets whether to enable the access to the file system in the application. By defa ...@@ -137,7 +152,7 @@ Sets whether to enable the access to the file system in the application. By defa
fileFromUrlAccess(fileFromUrlAccess: boolean) fileFromUrlAccess(fileFromUrlAccess: boolean)
Sets whether to allow the use of JavaScript scripts on web pages for access to content in the application file system. By default, this feature is disabled. Access to the files specified through [$rawfile(filepath/filename)](../../ui/ts-resource-access.md) are not affected by this attribute. Sets whether to allow the use of JavaScript scripts on web pages for access to content in the application file system. By default, this feature is disabled. Access to the files in **rawfile** specified through [$rawfile(filepath/filename)](../../quick-start/resource-categories-and-access.md) are not affected by the setting.
**Parameters** **Parameters**
...@@ -152,7 +167,7 @@ Sets whether to allow the use of JavaScript scripts on web pages for access to c ...@@ -152,7 +167,7 @@ Sets whether to allow the use of JavaScript scripts on web pages for access to c
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -180,7 +195,7 @@ Sets whether to enable automatic image loading. By default, this feature is enab ...@@ -180,7 +195,7 @@ Sets whether to enable automatic image loading. By default, this feature is enab
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -193,7 +208,7 @@ Sets whether to enable automatic image loading. By default, this feature is enab ...@@ -193,7 +208,7 @@ Sets whether to enable automatic image loading. By default, this feature is enab
### javaScriptProxy ### javaScriptProxy
javaScriptProxy(javaScriptProxy: { object: object, name: string, methodList: Array\<string\>, javaScriptProxy(javaScriptProxy: { object: object, name: string, methodList: Array\<string\>,
controller: WebController }) controller: WebController | WebviewController})
Injects a JavaScript object into the window. Methods of this object can be invoked in the window. The parameters cannot be updated. Injects a JavaScript object into the window. Methods of this object can be invoked in the window. The parameters cannot be updated.
...@@ -201,10 +216,10 @@ Injects a JavaScript object into the window. Methods of this object can be invok ...@@ -201,10 +216,10 @@ Injects a JavaScript object into the window. Methods of this object can be invok
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ---------- | --------------- | ---- | ---- | ------------------------- | | ---------- | --------------- | ---- | ---- | ------------------------- |
| object | object | Yes | - | Object to be registered. Methods can be declared, but not attributes. | | object | object | Yes | - | Object to be registered. Methods can be declared, but attributes cannot. |
| name | string | Yes | - | Name of the object to be registered, which is the same as that invoked in the window.| | name | string | Yes | - | Name of the object to be registered, which is the same as that invoked in the window.|
| methodList | Array\<string\> | Yes | - | Methods of the JavaScript object to be registered at the application side. | | methodList | Array\<string\> | Yes | - | Methods of the JavaScript object to be registered at the application side. |
| controller | [WebController](#webcontroller) | No | - | Controller. | | controller | [WebController](#webcontroller) or WebviewController | Yes | - | Controller. |
**Example** **Example**
...@@ -213,16 +228,49 @@ Injects a JavaScript object into the window. Methods of this object can be invok ...@@ -213,16 +228,49 @@ Injects a JavaScript object into the window. Methods of this object can be invok
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
testObj = { testObj = {
test: (data1, data2, data3) => { test: (data1, data2, data3) => {
console.log("data1:" + data1); console.log("data1:" + data1)
console.log("data2:" + data2); console.log("data2:" + data2)
console.log("data3:" + data3); console.log("data3:" + data3)
return "AceString"; return "AceString"
}, },
toString: () => { toString: () => {
console.log('toString' + "interface instead."); console.log('toString' + "interface instead.")
}
}
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.javaScriptAccess(true)
.javaScriptProxy({
object: this.testObj,
name: "objName",
methodList: ["test", "toString"],
controller: this.controller,
})
}
}
}
```
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController()
testObj = {
test: (data1, data2, data3) => {
console.log("data1:" + data1)
console.log("data2:" + data2)
console.log("data3:" + data3)
return "AceString"
},
toString: () => {
console.log('toString' + "interface instead.")
} }
} }
build() { build() {
...@@ -259,7 +307,7 @@ Sets whether JavaScript scripts can be executed. By default, JavaScript scripts ...@@ -259,7 +307,7 @@ Sets whether JavaScript scripts can be executed. By default, JavaScript scripts
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -288,8 +336,8 @@ Sets whether to enable loading of HTTP and HTTPS hybrid content can be loaded. B ...@@ -288,8 +336,8 @@ Sets whether to enable loading of HTTP and HTTPS hybrid content can be loaded. B
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
@State mode: MixedMode = MixedMode.All; @State mode: MixedMode = MixedMode.All
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -318,7 +366,7 @@ Sets whether to enable access to online images through HTTP and HTTPS. By defaul ...@@ -318,7 +366,7 @@ Sets whether to enable access to online images through HTTP and HTTPS. By defaul
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -347,7 +395,7 @@ Sets whether to enable zoom gestures. By default, this feature is enabled. ...@@ -347,7 +395,7 @@ Sets whether to enable zoom gestures. By default, this feature is enabled.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -376,7 +424,7 @@ Sets whether to load web pages by using the overview mode. By default, this feat ...@@ -376,7 +424,7 @@ Sets whether to load web pages by using the overview mode. By default, this feat
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -405,7 +453,7 @@ Sets whether to enable database access. By default, this feature is disabled. ...@@ -405,7 +453,7 @@ Sets whether to enable database access. By default, this feature is disabled.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -434,7 +482,7 @@ Sets whether to enable geolocation access. By default, this feature is enabled. ...@@ -434,7 +482,7 @@ Sets whether to enable geolocation access. By default, this feature is enabled.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -463,8 +511,8 @@ Sets whether a manual click is required for video playback. ...@@ -463,8 +511,8 @@ Sets whether a manual click is required for video playback.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
@State access: boolean = true; @State access: boolean = true
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -474,6 +522,35 @@ Sets whether a manual click is required for video playback. ...@@ -474,6 +522,35 @@ Sets whether a manual click is required for video playback.
} }
``` ```
### multiWindowAccess<sup>9+</sup>
multiWindowAccess(multiWindow: boolean)
Sets whether to enable the multi-window permission.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------------- | ------- | ---- | ---- | ----------------- |
| multiWindow | boolean | Yes | false | Whether to enable the multi-window permission.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.multiWindowAccess(true)
}
}
}
```
### cacheMode ### cacheMode
cacheMode(cacheMode: CacheMode) cacheMode(cacheMode: CacheMode)
...@@ -493,8 +570,8 @@ Sets the cache mode. ...@@ -493,8 +570,8 @@ Sets the cache mode.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
@State mode: CacheMode = CacheMode.None; @State mode: CacheMode = CacheMode.None
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -504,7 +581,7 @@ Sets the cache mode. ...@@ -504,7 +581,7 @@ Sets the cache mode.
} }
``` ```
### textZoomRatio ### textZoomRatio<sup>9+</sup>
textZoomRatio(textZoomRatio: number) textZoomRatio(textZoomRatio: number)
...@@ -523,8 +600,8 @@ Sets the text zoom ratio of the page. The default value is **100**, which indica ...@@ -523,8 +600,8 @@ Sets the text zoom ratio of the page. The default value is **100**, which indica
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
@State atio: number = 150; @State atio: number = 150
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -534,6 +611,36 @@ Sets the text zoom ratio of the page. The default value is **100**, which indica ...@@ -534,6 +611,36 @@ Sets the text zoom ratio of the page. The default value is **100**, which indica
} }
``` ```
### initialScale<sup>9+</sup>
initialScale(percent: number)
Sets the scale factor of the entire page. The default value is 100%.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------------ | ------ | ---- | ---- | --------------- |
| percent | number | Yes | 100 | Scale factor of the entire page.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
@State percent: number = 100
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.initialScale(this.percent)
}
}
}
```
### userAgent ### userAgent
userAgent(userAgent: string) userAgent(userAgent: string)
...@@ -553,8 +660,8 @@ Sets the user agent. ...@@ -553,8 +660,8 @@ Sets the user agent.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
@State userAgent:string = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36'; @State userAgent:string = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36'
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -564,7 +671,37 @@ Sets the user agent. ...@@ -564,7 +671,37 @@ Sets the user agent.
} }
``` ```
> **NOTE** ### webDebuggingAccess<sup>9+</sup>
webDebuggingAccess(webDebuggingAccess: boolean)
Sets whether to enable web debugging.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| --------- | ------ | ---- | ---- | --------- |
| webDebuggingAccess | boolean | Yes | false | Whether to enable web debugging.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
@State webDebuggingAccess: boolean = true
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.webDebuggingAccess(this.webDebuggingAccess)
}
}
}
```
> **NOTE**<br>
> >
> Only the following universal attributes are supported: [width](ts-universal-attributes-size.md#Attributes), [height](ts-universal-attributes-size.md#attributes), [padding](ts-universal-attributes-size.md#Attributes), [margin](ts-universal-attributes-size.md#attributes), and [border](ts-universal-attributes-border.md#attributes). > Only the following universal attributes are supported: [width](ts-universal-attributes-size.md#Attributes), [height](ts-universal-attributes-size.md#attributes), [padding](ts-universal-attributes-size.md#Attributes), [margin](ts-universal-attributes-size.md#attributes), and [border](ts-universal-attributes-border.md#attributes).
...@@ -599,7 +736,7 @@ Triggered when **alert()** is invoked to display an alert dialog box on the web ...@@ -599,7 +736,7 @@ Triggered when **alert()** is invoked to display an alert dialog box on the web
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -623,7 +760,7 @@ Triggered when **alert()** is invoked to display an alert dialog box on the web ...@@ -623,7 +760,7 @@ Triggered when **alert()** is invoked to display an alert dialog box on the web
event.result.handleCancel() event.result.handleCancel()
} }
}) })
return true; return true
}) })
} }
} }
...@@ -634,7 +771,7 @@ Triggered when **alert()** is invoked to display an alert dialog box on the web ...@@ -634,7 +771,7 @@ Triggered when **alert()** is invoked to display an alert dialog box on the web
onBeforeUnload(callback: (event?: { url: string; message: string; result: JsResult }) => boolean) onBeforeUnload(callback: (event?: { url: string; message: string; result: JsResult }) => boolean)
Triggered when the current page is about to exit after the user refreshes or closes the page. If the user refreshes the page, this callback is triggered only when the page has obtained focus. Triggered when the current page is about to exit after the user refreshes or closes the page. If the user refreshes the page, this callback is invoked only when the page has obtained focus.
**Parameters** **Parameters**
...@@ -657,14 +794,14 @@ Triggered when the current page is about to exit after the user refreshes or clo ...@@ -657,14 +794,14 @@ Triggered when the current page is about to exit after the user refreshes or clo
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.onBeforeUnload((event) => { .onBeforeUnload((event) => {
console.log("event.url:" + event.url); console.log("event.url:" + event.url)
console.log("event.message:" + event.message); console.log("event.message:" + event.message)
AlertDialog.show({ AlertDialog.show({
title: 'onBeforeUnload', title: 'onBeforeUnload',
message: 'text', message: 'text',
...@@ -684,7 +821,7 @@ Triggered when the current page is about to exit after the user refreshes or clo ...@@ -684,7 +821,7 @@ Triggered when the current page is about to exit after the user refreshes or clo
event.result.handleCancel() event.result.handleCancel()
} }
}) })
return true; return true
}) })
} }
} }
...@@ -718,15 +855,15 @@ Triggered when **confirm()** is invoked by the web page. ...@@ -718,15 +855,15 @@ Triggered when **confirm()** is invoked by the web page.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.onConfirm((event) => { .onConfirm((event) => {
console.log("event.url:" + event.url); console.log("event.url:" + event.url)
console.log("event.message:" + event.message); console.log("event.message:" + event.message)
console.log("event.result:" + event.result); console.log("event.result:" + event.result)
AlertDialog.show({ AlertDialog.show({
title: 'onConfirm', title: 'onConfirm',
message: 'text', message: 'text',
...@@ -746,7 +883,7 @@ Triggered when **confirm()** is invoked by the web page. ...@@ -746,7 +883,7 @@ Triggered when **confirm()** is invoked by the web page.
event.result.handleCancel() event.result.handleCancel()
} }
}) })
return true; return true
}) })
} }
} }
...@@ -778,15 +915,15 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul ...@@ -778,15 +915,15 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.onPrompt((event) => { .onPrompt((event) => {
console.log("url:" + event.url); console.log("url:" + event.url)
console.log("message:" + event.message); console.log("message:" + event.message)
console.log("value:" + event.value); console.log("value:" + event.value)
AlertDialog.show({ AlertDialog.show({
title: 'onPrompt', title: 'onPrompt',
message: 'text', message: 'text',
...@@ -806,7 +943,7 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul ...@@ -806,7 +943,7 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul
event.result.handleCancel() event.result.handleCancel()
} }
}) })
return true; return true
}) })
} }
} }
...@@ -838,17 +975,17 @@ Triggered to notify the host application of a JavaScript console message. ...@@ -838,17 +975,17 @@ Triggered to notify the host application of a JavaScript console message.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.onConsole((event) => { .onConsole((event) => {
console.log('getMessage:' + event.message.getMessage()); console.log('getMessage:' + event.message.getMessage())
console.log('getSourceId:' + event.message.getSourceId()); console.log('getSourceId:' + event.message.getSourceId())
console.log('getLineNumber:' + event.message.getLineNumber()); console.log('getLineNumber:' + event.message.getLineNumber())
console.log('getMessageLevel:' + event.message.getMessageLevel()); console.log('getMessageLevel:' + event.message.getMessageLevel())
return false; return false
}) })
} }
} }
...@@ -875,17 +1012,17 @@ onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisp ...@@ -875,17 +1012,17 @@ onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisp
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.onDownloadStart((event) => { .onDownloadStart((event) => {
console.log('url:' + event.url); console.log('url:' + event.url)
console.log('userAgent:' + event.userAgent); console.log('userAgent:' + event.userAgent)
console.log('contentDisposition:' + event.contentDisposition); console.log('contentDisposition:' + event.contentDisposition)
console.log('contentLength:' + event.contentLength); console.log('contentLength:' + event.contentLength)
console.log('mimetype:' + event.mimetype); console.log('mimetype:' + event.mimetype)
}) })
} }
} }
...@@ -912,23 +1049,23 @@ Triggered when an error occurs during web page loading. For better results, simp ...@@ -912,23 +1049,23 @@ Triggered when an error occurs during web page loading. For better results, simp
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.onErrorReceive((event) => { .onErrorReceive((event) => {
console.log('getErrorInfo:' + event.error.getErrorInfo()); console.log('getErrorInfo:' + event.error.getErrorInfo())
console.log('getErrorCode:' + event.error.getErrorCode()); console.log('getErrorCode:' + event.error.getErrorCode())
console.log('url:' + event.request.getRequestUrl()); console.log('url:' + event.request.getRequestUrl())
console.log('isMainFrame:' + event.request.isMainFrame()); console.log('isMainFrame:' + event.request.isMainFrame())
console.log('isRedirect:' + event.request.isRedirect()); console.log('isRedirect:' + event.request.isRedirect())
console.log('isRequestGesture:' + event.request.isRequestGesture()); console.log('isRequestGesture:' + event.request.isRequestGesture())
console.log('getRequestHeader_headerKey:' + event.request.getRequestHeader().toString()); console.log('getRequestHeader_headerKey:' + event.request.getRequestHeader().toString())
let result = event.request.getRequestHeader(); let result = event.request.getRequestHeader()
console.log('The request header result size is ' + result.length); console.log('The request header result size is ' + result.length)
for (let i of result) { for (let i of result) {
console.log('The request header key is : ' + i.headerKey + ', value is : ' + i.headerValue); console.log('The request header key is : ' + i.headerKey + ', value is : ' + i.headerValue)
} }
}) })
} }
...@@ -956,30 +1093,30 @@ Triggered when an HTTP error (the response code is greater than or equal to 400) ...@@ -956,30 +1093,30 @@ Triggered when an HTTP error (the response code is greater than or equal to 400)
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.onHttpErrorReceive((event) => { .onHttpErrorReceive((event) => {
console.log('url:' + event.request.getRequestUrl()); console.log('url:' + event.request.getRequestUrl())
console.log('isMainFrame:' + event.request.isMainFrame()); console.log('isMainFrame:' + event.request.isMainFrame())
console.log('isRedirect:' + event.request.isRedirect()); console.log('isRedirect:' + event.request.isRedirect())
console.log('isRequestGesture:' + event.request.isRequestGesture()); console.log('isRequestGesture:' + event.request.isRequestGesture())
console.log('getResponseData:' + event.response.getResponseData()); console.log('getResponseData:' + event.response.getResponseData())
console.log('getResponseEncoding:' + event.response.getResponseEncoding()); console.log('getResponseEncoding:' + event.response.getResponseEncoding())
console.log('getResponseMimeType:' + event.response.getResponseMimeType()); console.log('getResponseMimeType:' + event.response.getResponseMimeType())
console.log('getResponseCode:' + event.response.getResponseCode()); console.log('getResponseCode:' + event.response.getResponseCode())
console.log('getReasonMessage:' + event.response.getReasonMessage()); console.log('getReasonMessage:' + event.response.getReasonMessage())
let result = event.request.getRequestHeader(); let result = event.request.getRequestHeader()
console.log('The request header result size is ' + result.length); console.log('The request header result size is ' + result.length)
for (let i of result) { for (let i of result) {
console.log('The request header key is : ' + i.headerKey + ' , value is : ' + i.headerValue); console.log('The request header key is : ' + i.headerKey + ' , value is : ' + i.headerValue)
} }
let resph = event.response.getResponseHeader(); let resph = event.response.getResponseHeader()
console.log('The response header result size is ' + resph.length); console.log('The response header result size is ' + resph.length)
for (let i of resph) { for (let i of resph) {
console.log('The response header key is : ' + i.headerKey + ' , value is : ' + i.headerValue); console.log('The response header key is : ' + i.headerKey + ' , value is : ' + i.headerValue)
} }
}) })
} }
...@@ -1007,13 +1144,13 @@ Triggered when the web page starts to be loaded. This API is triggered only for ...@@ -1007,13 +1144,13 @@ Triggered when the web page starts to be loaded. This API is triggered only for
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.onPageBegin((event) => { .onPageBegin((event) => {
console.log('url:' + event.url); console.log('url:' + event.url)
}) })
} }
} }
...@@ -1040,13 +1177,13 @@ Triggered when the web page loading is complete. This API is triggered only for ...@@ -1040,13 +1177,13 @@ Triggered when the web page loading is complete. This API is triggered only for
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.onPageEnd((event) => { .onPageEnd((event) => {
console.log('url:' + event.url); console.log('url:' + event.url)
}) })
} }
} }
...@@ -1072,7 +1209,7 @@ Triggered when the web page loading progress changes. ...@@ -1072,7 +1209,7 @@ Triggered when the web page loading progress changes.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
...@@ -1104,7 +1241,7 @@ Triggered when the document title of the web page is changed. ...@@ -1104,7 +1241,7 @@ Triggered when the document title of the web page is changed.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
...@@ -1137,13 +1274,13 @@ Triggered when loading of the web page is complete. This API is used by an appli ...@@ -1137,13 +1274,13 @@ Triggered when loading of the web page is complete. This API is used by an appli
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.onRefreshAccessedHistory((event) => { .onRefreshAccessedHistory((event) => {
console.log('url:' + event.url + ' isReload:' + event.isRefreshed); console.log('url:' + event.url + ' isReload:' + event.isRefreshed)
}) })
} }
} }
...@@ -1169,13 +1306,13 @@ Triggered when the rendering process exits abnormally. ...@@ -1169,13 +1306,13 @@ Triggered when the rendering process exits abnormally.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'chrome://crash/', controller: this.controller }) Web({ src: 'chrome://crash/', controller: this.controller })
.onRenderExited((event) => { .onRenderExited((event) => {
console.log('reason:' + event.renderExitReason); console.log('reason:' + event.renderExitReason)
}) })
} }
} }
...@@ -1199,7 +1336,7 @@ Triggered to process an HTML form whose input type is **file**, in response to t ...@@ -1199,7 +1336,7 @@ Triggered to process an HTML form whose input type is **file**, in response to t
| Type | Description | | Type | Description |
| ------- | ----------------------------------- | | ------- | ----------------------------------- |
| boolean | The value **true** means that the pop-up window provided by the system is displayed. The value **true** means that the default web pop-up window is displayed.| | boolean | The value **true** means that the pop-up window provided by the system is displayed. The value **false** means that the default web pop-up window is displayed.|
**Example** **Example**
...@@ -1208,7 +1345,7 @@ Triggered to process an HTML form whose input type is **file**, in response to t ...@@ -1208,7 +1345,7 @@ Triggered to process an HTML form whose input type is **file**, in response to t
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
...@@ -1231,7 +1368,72 @@ Triggered to process an HTML form whose input type is **file**, in response to t ...@@ -1231,7 +1368,72 @@ Triggered to process an HTML form whose input type is **file**, in response to t
event.result.handleFileList(fileList) event.result.handleFileList(fileList)
} }
}) })
return true; return true
})
}
}
}
```
### onResourceLoad<sup>9+</sup>
onResourceLoad(callback: (event: {url: string}) => void)
Invoked to notify the **\<Web>** component of the URL of the loaded resource file.
**Parameters**
| Name | Type | Description |
| ---- | ---------------------------------------- | --------- |
| url | string | URL of the loaded resource file.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onResourceLoad((event) => {
console.log('onResourceLoad: ' + event.url)
})
}
}
}
```
### onScaleChange<sup>9+</sup>
onScaleChange(callback: (event: {oldScale: number, newScale: number}) => void)
Invoked when the display ratio of this page changes.
**Parameters**
| Name | Type | Description |
| ---- | ---------------------------------------- | --------- |
| oldScale | number | Display ratio of the page before the change.|
| newScale | number | Display ratio of the page after the change.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onScaleChange((event) => {
console.log('onScaleChange changed from ' + event.oldScale + ' to ' + event.newScale)
}) })
} }
} }
...@@ -1263,14 +1465,14 @@ Triggered when the **\<Web>** component is about to access a URL. This API is us ...@@ -1263,14 +1465,14 @@ Triggered when the **\<Web>** component is about to access a URL. This API is us
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.onUrlLoadIntercept((event) => { .onUrlLoadIntercept((event) => {
console.log('onUrlLoadIntercept ' + event.data.toString()) console.log('onUrlLoadIntercept ' + event.data.toString())
return true; return true
}) })
} }
} }
...@@ -1281,7 +1483,7 @@ Triggered when the **\<Web>** component is about to access a URL. This API is us ...@@ -1281,7 +1483,7 @@ Triggered when the **\<Web>** component is about to access a URL. This API is us
onInterceptRequest(callback: (event?: { request: WebResourceRequest}) => WebResourceResponse) onInterceptRequest(callback: (event?: { request: WebResourceRequest}) => WebResourceResponse)
Triggered when the **\<Web>** component is about to access a URL. This API is used to block the URL and return the response data. Invoked when the **\<Web>** component is about to access a URL. This API is used to block the URL and return the response data.
**Parameters** **Parameters**
...@@ -1302,9 +1504,9 @@ Triggered when the **\<Web>** component is about to access a URL. This API is us ...@@ -1302,9 +1504,9 @@ Triggered when the **\<Web>** component is about to access a URL. This API is us
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
responseweb: WebResourceResponse = new WebResourceResponse(); responseweb: WebResourceResponse = new WebResourceResponse()
heads:Header[] = new Array(); heads:Header[] = new Array()
@State webdata: string = "<!DOCTYPE html>\n" + @State webdata: string = "<!DOCTYPE html>\n" +
"<html>\n"+ "<html>\n"+
"<head>\n"+ "<head>\n"+
...@@ -1318,7 +1520,7 @@ Triggered when the **\<Web>** component is about to access a URL. This API is us ...@@ -1318,7 +1520,7 @@ Triggered when the **\<Web>** component is about to access a URL. This API is us
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.onInterceptRequest((event) => { .onInterceptRequest((event) => {
console.log('url:' + event.request.getRequestUrl()); console.log('url:' + event.request.getRequestUrl())
var head1:Header = { var head1:Header = {
headerKey:"Connection", headerKey:"Connection",
headerValue:"keep-alive" headerValue:"keep-alive"
...@@ -1327,15 +1529,15 @@ Triggered when the **\<Web>** component is about to access a URL. This API is us ...@@ -1327,15 +1529,15 @@ Triggered when the **\<Web>** component is about to access a URL. This API is us
headerKey:"Cache-Control", headerKey:"Cache-Control",
headerValue:"no-cache" headerValue:"no-cache"
} }
var length = this.heads.push(head1); var length = this.heads.push(head1)
length = this.heads.push(head2); length = this.heads.push(head2)
this.responseweb.setResponseHeader(this.heads); this.responseweb.setResponseHeader(this.heads)
this.responseweb.setResponseData(this.webdata); this.responseweb.setResponseData(this.webdata)
this.responseweb.setResponseEncoding('utf-8'); this.responseweb.setResponseEncoding('utf-8')
this.responseweb.setResponseMimeType('text/html'); this.responseweb.setResponseMimeType('text/html')
this.responseweb.setResponseCode(200); this.responseweb.setResponseCode(200)
this.responseweb.setReasonMessage('OK'); this.responseweb.setReasonMessage('OK')
return this.responseweb; return this.responseweb
}) })
} }
} }
...@@ -1346,7 +1548,7 @@ Triggered when the **\<Web>** component is about to access a URL. This API is us ...@@ -1346,7 +1548,7 @@ Triggered when the **\<Web>** component is about to access a URL. This API is us
onHttpAuthRequest(callback: (event?: { handler: HttpAuthHandler, host: string, realm: string}) => boolean) onHttpAuthRequest(callback: (event?: { handler: HttpAuthHandler, host: string, realm: string}) => boolean)
Triggered when an HTTP authentication request is received. Invoked when an HTTP authentication request is received.
**Parameters** **Parameters**
...@@ -1370,8 +1572,8 @@ Triggered when an HTTP authentication request is received. ...@@ -1370,8 +1572,8 @@ Triggered when an HTTP authentication request is received.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
httpAuth: boolean = false; httpAuth: boolean = false
build() { build() {
Column() { Column() {
...@@ -1383,13 +1585,13 @@ Triggered when an HTTP authentication request is received. ...@@ -1383,13 +1585,13 @@ Triggered when an HTTP authentication request is received.
primaryButton: { primaryButton: {
value: 'cancel', value: 'cancel',
action: () => { action: () => {
event.handler.cancel(); event.handler.cancel()
} }
}, },
secondaryButton: { secondaryButton: {
value: 'ok', value: 'ok',
action: () => { action: () => {
this.httpAuth = event.handler.isHttpAuthInfoSaved(); this.httpAuth = event.handler.isHttpAuthInfoSaved()
if (this.httpAuth == false) { if (this.httpAuth == false) {
web_webview.WebDataBase.saveHttpAuthCredentials( web_webview.WebDataBase.saveHttpAuthCredentials(
event.host, event.host,
...@@ -1397,15 +1599,15 @@ Triggered when an HTTP authentication request is received. ...@@ -1397,15 +1599,15 @@ Triggered when an HTTP authentication request is received.
"2222", "2222",
"2222" "2222"
) )
event.handler.cancel(); event.handler.cancel()
} }
} }
}, },
cancel: () => { cancel: () => {
event.handler.cancel(); event.handler.cancel()
} }
}) })
return true; return true
}) })
} }
} }
...@@ -1432,7 +1634,7 @@ Invoked when an SSL error occurs during resource loading. ...@@ -1432,7 +1634,7 @@ Invoked when an SSL error occurs during resource loading.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
...@@ -1444,20 +1646,20 @@ Invoked when an SSL error occurs during resource loading. ...@@ -1444,20 +1646,20 @@ Invoked when an SSL error occurs during resource loading.
primaryButton: { primaryButton: {
value: 'confirm', value: 'confirm',
action: () => { action: () => {
event.handler.handleConfirm(); event.handler.handleConfirm()
} }
}, },
secondaryButton: { secondaryButton: {
value: 'cancel', value: 'cancel',
action: () => { action: () => {
event.handler.handleCancel(); event.handler.handleCancel()
} }
}, },
cancel: () => { cancel: () => {
event.handler.handleCancel(); event.handler.handleCancel()
} }
}) })
return true; return true
}) })
} }
} }
...@@ -1466,7 +1668,7 @@ Invoked when an SSL error occurs during resource loading. ...@@ -1466,7 +1668,7 @@ Invoked when an SSL error occurs during resource loading.
### onClientAuthenticationRequest<sup>9+</sup> ### onClientAuthenticationRequest<sup>9+</sup>
onClientAuthenticationRequest(callback: (event: {handler : ClientAuthenticationHandler, host : string, port : number, keyTypes : Array<string>, issuers : Array<string>}) => void) onClientAuthenticationRequest(callback: (event: {handler : ClientAuthenticationHandler, host : string, port : number, keyTypes : Array\<string>, issuers : Array\<string>}) => void)
Invoked when an SSL client certificate request is received. Invoked when an SSL client certificate request is received.
...@@ -1477,8 +1679,8 @@ Invoked when an SSL client certificate request is received. ...@@ -1477,8 +1679,8 @@ Invoked when an SSL client certificate request is received.
| handler | [ClientAuthenticationHandler](#clientauthenticationhandler9) | The user's operation.| | handler | [ClientAuthenticationHandler](#clientauthenticationhandler9) | The user's operation.|
| host | string | Host name of the server that requests a certificate.| | host | string | Host name of the server that requests a certificate.|
| port | number | Port number of the server that requests a certificate.| | port | number | Port number of the server that requests a certificate.|
| keyTypes| Array<string> | Acceptable asymmetric private key types.| | keyTypes| Array\<string> | Acceptable asymmetric private key types.|
| issuers | Array<string> | Issuer of the certificate that matches the private key.| | issuers | Array\<string> | Issuer of the certificate that matches the private key.|
**Example** **Example**
```ts ```ts
...@@ -1487,7 +1689,7 @@ Invoked when an SSL client certificate request is received. ...@@ -1487,7 +1689,7 @@ Invoked when an SSL client certificate request is received.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
...@@ -1499,20 +1701,20 @@ Invoked when an SSL client certificate request is received. ...@@ -1499,20 +1701,20 @@ Invoked when an SSL client certificate request is received.
primaryButton: { primaryButton: {
value: 'confirm', value: 'confirm',
action: () => { action: () => {
event.handler.confirm("/system/etc/user.pk8", "/system/etc/chain-user.pem"); event.handler.confirm("/system/etc/user.pk8", "/system/etc/chain-user.pem")
} }
}, },
secondaryButton: { secondaryButton: {
value: 'cancel', value: 'cancel',
action: () => { action: () => {
event.handler.cancel(); event.handler.cancel()
} }
}, },
cancel: () => { cancel: () => {
event.handler.ignore(); event.handler.ignore()
} }
}) })
return true; return true
}) })
} }
} }
...@@ -1538,7 +1740,7 @@ Invoked when a permission request is received. ...@@ -1538,7 +1740,7 @@ Invoked when a permission request is received.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -1549,17 +1751,17 @@ Invoked when a permission request is received. ...@@ -1549,17 +1751,17 @@ Invoked when a permission request is received.
primaryButton: { primaryButton: {
value: 'deny', value: 'deny',
action: () => { action: () => {
event.request.deny(); event.request.deny()
} }
}, },
secondaryButton: { secondaryButton: {
value: 'onConfirm', value: 'onConfirm',
action: () => { action: () => {
event.request.grant(event.request.getAccessibleResource()); event.request.grant(event.request.getAccessibleResource())
} }
}, },
cancel: () => { cancel: () => {
event.request.deny(); event.request.deny()
} }
}) })
}) })
...@@ -1568,24 +1770,200 @@ Invoked when a permission request is received. ...@@ -1568,24 +1770,200 @@ Invoked when a permission request is received.
} }
``` ```
### onContextMenuShow<sup>9+</sup> ### onContextMenuShow<sup>9+</sup>
onContextMenuShow(callback: (event?: { param: WebContextMenuParam, result: WebContextMenuResult }) => boolean)
Invoked when a context menu is displayed upon a long press on a specific element (such as an image or link).
**Parameters**
| Name | Type | Description |
| ------- | ------------------------------------ | ---------------- |
| param | [WebContextMenuParam](#webcontextmenuparam9) | Parameters related to the context menu.|
| result | [WebContextMenuResult](#webcontextmenuresult9) | Result of the context menu.|
**Return value**
| Type | Description |
| ------ | -------------------- |
| boolean | The value **true** means a custom menu, and **false** means the default menu.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onContextMenuShow((event) => {
console.info("x coord = " + event.param.x())
console.info("link url = " + event.param.getLinkUrl())
return true
})
}
}
}
```
### onScroll<sup>9+</sup>
onScroll(callback: (event: {xOffset: number, yOffset: number}) => void)
Invoked when the scrollbar of the page scrolls.
**Parameters**
| Name | Type | Description |
| ------- | ------------------------------------ | ---------------- |
| xOffset | number | Position of the scrollbar on the x-axis.|
| yOffset | number | Position of the scrollbar on the y-axis.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onScroll((event) => {
console.info("x = " + event.xOffset)
console.info("y = " + event.yOffset)
})
}
}
}
```
### onGeolocationShow
onGeolocationShow(callback: (event?: { origin: string, geolocation: JsGeolocation }) => void)
Registers a callback for receiving a request to obtain the geolocation information.
**Parameters**
| Name | Type | Description |
| ----------- | ------------------------------- | ---------------- |
| origin | string | Index of the origin. |
| geolocation | [JsGeolocation](#jsgeolocation) | The user's operation.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller:WebController = new WebController()
build() {
Column() {
Web({ src:'www.example.com', controller:this.controller })
.geolocationAccess(true)
.onGeolocationShow((event) => {
AlertDialog.show({
title: 'title',
message: 'text',
confirm: {
value: 'onConfirm',
action: () => {
event.geolocation.invoke(event.origin, true, true)
}
},
cancel: () => {
event.geolocation.invoke(event.origin, false, true)
}
})
})
}
}
}
```
### onGeolocationHide
onGeolocationHide(callback: () => void)
Triggered to notify the user that the request for obtaining the geolocation information received when **[onGeolocationShow](#ongeolocationshow)** is called has been canceled.
**Parameters**
| Name | Type | Description |
| ----------- | ------------------------------- | ---------------- |
| callback | () => void | Callback invoked when the request for obtaining geolocation information has been canceled. |
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller:WebController = new WebController()
build() {
Column() {
Web({ src:'www.example.com', controller:this.controller })
.geolocationAccess(true)
.onGeolocationHide(() => {
console.log("onGeolocationHide...")
})
}
}
}
```
### onFullScreenEnter<sup>9+</sup>
onFullScreenEnter(callback: (event: { handler: FullScreenExitHandler }) => void)
Registers a callback for the component's entering into full screen mode.
**Parameters**
| Name | Type | Description |
| ----------- | ------------------------------- | ---------------- |
| handler | [FullScreenExitHandler](#fullscreenexithandler9) | Function handle for exiting full screen mode.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller:WebController = new WebController()
handler: FullScreenExitHandler = null
build() {
Column() {
Web({ src:'www.example.com', controller:this.controller })
.onFullScreenEnter((event) => {
console.log("onFullScreenEnter...")
this.handler = event.handler
})
}
}
}
```
### onFullScreenExit<sup>9+</sup>
onContextMenuShow(callback: (event?: { param: WebContextMenuParam, result: WebContextMenuResult }) => boolean) onFullScreenExit(callback: () => void)
Invoked when a context menu is displayed upon a long press on a specific element (such as an image or link). Registers a callback for the component's exiting full screen mode.
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Description |
| ------- | ------------------------------------ | ---------------- | | ----------- | ------------------------------- | ---------------- |
| param | [WebContextMenuParam](#webcontextmenuparam9) | Parameters related to the context menu.| | callback | () => void | Callback invoked when the component exits full screen mode.|
| result | [WebContextMenuResult](#webcontextmenuresult9) | Result of the context menu.|
**Return value**
| Type | Description |
| ------ | -------------------- |
| boolean | The value **true** means a custom menu, and **false** means the default menu.|
**Example** **Example**
...@@ -1594,32 +1972,37 @@ Invoked when a context menu is displayed upon a long press on a specific element ...@@ -1594,32 +1972,37 @@ Invoked when a context menu is displayed upon a long press on a specific element
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller:WebController = new WebController()
handler: FullScreenExitHandler = null
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src:'www.example.com', controller:this.controller })
.onContextMenuShow((event) => { .onFullScreenExit(() => {
console.info("x coord = " + event.param.x()); console.log("onFullScreenExit...")
console.info("link url = " + event.param.getLinkUrl()); this.handler.exitFullScreen()
return true; })
.onFullScreenEnter((event) => {
this.handler = event.handler
}) })
} }
} }
} }
``` ```
### onScroll<sup>9+</sup> ### onWindowNew<sup>9+</sup>
onScroll(callback: (event: {xOffset: number, yOffset: number}) => void) onWindowNew(callback: (event: {isAlert: boolean, isUserTrigger: boolean, targetUrl: string, handler: ControllerHandler}) => void)
Invoked when the scrollbar of the page scrolls. Registers a callback for window creation.
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Description |
| ------- | ------------------------------------ | ---------------- | | ----------- | ------------------------------- | ---------------- |
| xOffset | number | Position of the scrollbar on the x-axis.| | isAlert | boolean | Whether to open the target URL in a new window. The value **true** means to open the target URL in a new window, and **false** means to open the target URL in a new tab.|
| yOffset | number | Position of the scrollbar on the y-axis.| | isUserTrigger | boolean | Whether the creation is triggered by the user. The value **true** means that the creation is triggered by the user, and **false** means the opposite.|
| targetUrl | string | Target URL.|
| handler | [ControllerHandler](#controllerhandler9) | **WebController** instance for setting the new window.|
**Example** **Example**
...@@ -1628,31 +2011,32 @@ Invoked when the scrollbar of the page scrolls. ...@@ -1628,31 +2011,32 @@ Invoked when the scrollbar of the page scrolls.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller:WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src:'www.example.com', controller: this.controller })
.onScroll((event) => { .multiWindowAccess(true)
console.info("x = " + event.xOffset); .onWindowNew((event) => {
console.info("y = " + event.yOffset); console.log("onWindowNew...")
var popController: WebController = new WebController()
event.handler.setWebController(popController)
}) })
} }
} }
} }
``` ```
### onGeolocationShow ### onWindowExit<sup>9+</sup>
onGeolocationShow(callback: (event?: { origin: string, geolocation: JsGeolocation }) => void) onWindowExit(callback: () => void)
Invoked when a request to obtain the geolocation information is received. Registers a callback for window closure.
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Description |
| ----------- | ------------------------------- | ---------------- | | ----------- | ------------------------------- | ---------------- |
| origin | string | Index of the origin. | | callback | () => void | Callback invoked when the window closes.|
| geolocation | [JsGeolocation](#jsgeolocation) | The user's operation.|
**Example** **Example**
...@@ -1661,25 +2045,12 @@ Invoked when a request to obtain the geolocation information is received. ...@@ -1661,25 +2045,12 @@ Invoked when a request to obtain the geolocation information is received.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller:WebController = new WebController(); controller:WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src:'www.example.com', controller:this.controller }) Web({ src:'www.example.com', controller: this.controller })
.geolocationAccess(true) .onWindowExit(() => {
.onGeolocationShow((event) => { console.log("onWindowExit...")
AlertDialog.show({
title: 'title',
message: 'text',
confirm: {
value: 'onConfirm',
action: () => {
event.geolocation.invoke(event.origin, true, true);
}
},
cancel: () => {
event.geolocation.invoke(event.origin, false, true);
}
})
}) })
} }
} }
...@@ -1712,7 +2083,7 @@ Obtains the log information of this console message. ...@@ -1712,7 +2083,7 @@ Obtains the log information of this console message.
| Type | Description | | Type | Description |
| ------ | ---------------------- | | ------ | ---------------------- |
| string | Log information of this console message.| | string | Log information of the console message.|
### getMessageLevel ### getMessageLevel
...@@ -1766,6 +2137,32 @@ Notifies the **\<Web>** component of the user's confirm operation in the dialog ...@@ -1766,6 +2137,32 @@ Notifies the **\<Web>** component of the user's confirm operation in the dialog
| ------ | ------ | ---- | ---- | ----------- | | ------ | ------ | ---- | ---- | ----------- |
| result | string | Yes | - | User input in the dialog box.| | result | string | Yes | - | User input in the dialog box.|
## FullScreenExitHandler<sup>9+</sup>
Defines a **FullScreenExitHandler** for listening for exiting full screen mode. For the sample code, see [onFullScreenEnter](#onfullscreenenter9).
### exitFullScreen<sup>9+</sup>
exitFullScreen(): void
Exits full screen mode.
## ControllerHandler<sup>9+</sup>
Defines a **WebController** for new web components. For the sample code, see [onWindowNew](#onwindownew9).
### setWebController<sup>9+</sup>
setWebController(controller: WebController): void
Sets a **WebController** object.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | ---- | ----------- |
| controller | WebController | Yes | - | **WebController** object to set.|
## WebResourceError ## WebResourceError
Implements the **WebResourceError** object. For details about the sample code, see [onErrorReceive](#onerrorreceive). Implements the **WebResourceError** object. For details about the sample code, see [onErrorReceive](#onerrorreceive).
...@@ -2133,42 +2530,42 @@ Implements an **SslErrorHandler** object. For details about the sample code, see ...@@ -2133,42 +2530,42 @@ Implements an **SslErrorHandler** object. For details about the sample code, see
handleCancel(): void handleCancel(): void
Instructs the web component to cancel the request. Cancels this request.
### handleConfirm<sup>9+</sup> ### handleConfirm<sup>9+</sup>
handleConfirm(): void handleConfirm(): void
Instructs the web component to continue using the SSL certificate. Continues using the SSL certificate.
## ClientAuthenticationHandler<sup>9+</sup> ## ClientAuthenticationHandler<sup>9+</sup>
Defines a **ClientAuthenticationHandler** object returned by the web component. For details about the sample code, see [onClientAuthenticationRequest](#onclientauthenticationrequest9). Defines a **ClientAuthenticationHandler** object returned by the **\<Web>** component. For details about the sample code, see [onClientAuthenticationRequest](#onclientauthenticationrequest9).
### confirm<sup>9+</sup> ### confirm<sup>9+</sup>
confirm(priKeyFile : string, certChainFile : string): void confirm(priKeyFile : string, certChainFile : string): void
Instructs the web component to use the specified private key and client certificate chain. Uses the specified private key and client certificate chain.
**Parameters** **Parameters**
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| -------- | ------ | ---- | ---------- | | -------- | ------ | ---- | ---------- |
| priKeyFile | string | Yes | File that stores the private key, including the directory and file name.| | priKeyFile | string | Yes | File that stores the private key, which is a directory including the file name.|
| certChainFile | string | Yes | File that stores the certificate chain, including the directory and file name.| | certChainFile | string | Yes | File that stores the certificate chain, which is a directory including the file name.|
### cancel<sup>9+</sup> ### cancel<sup>9+</sup>
cancel(): void cancel(): void
Instructs the web component to cancel the client certificate request sent by the same host and port server. No additional event will be reported for requests from the same host and port server. Cancels the client certificate request sent by the same host and port server. No additional event will be reported for requests from the same host and port server.
### ignore<sup>9+</sup> ### ignore<sup>9+</sup>
ignore(): void ignore(): void
Instructs the web component to ignore this request. Ignores this request.
## PermissionRequest<sup>9+</sup> ## PermissionRequest<sup>9+</sup>
...@@ -2224,7 +2621,7 @@ Provides the information about the context menu that is displayed when a page el ...@@ -2224,7 +2621,7 @@ Provides the information about the context menu that is displayed when a page el
x(): number x(): number
X coordinate of the context menu. Obtains the X coordinate of the context menu.
**Return value** **Return value**
...@@ -2236,7 +2633,7 @@ X coordinate of the context menu. ...@@ -2236,7 +2633,7 @@ X coordinate of the context menu.
y(): number y(): number
Y coordinate of the context menu. Obtains the Y coordinate of the context menu.
**Return value** **Return value**
...@@ -2254,7 +2651,7 @@ Obtains the URL of the destination link. ...@@ -2254,7 +2651,7 @@ Obtains the URL of the destination link.
| Type | Description | | Type | Description |
| --------------- | ----------------------- | | --------------- | ----------------------- |
| string | If it is the link that is being long pressed, the URL that has passed the security check is returned.| | string | If it is a link that is being long pressed, the URL that has passed the security check is returned.|
### getUnfilterendLinkUrl<sup>9+</sup> ### getUnfilterendLinkUrl<sup>9+</sup>
...@@ -2266,7 +2663,7 @@ Obtains the URL of the destination link. ...@@ -2266,7 +2663,7 @@ Obtains the URL of the destination link.
| Type | Description | | Type | Description |
| --------------- | ----------------------- | | --------------- | ----------------------- |
| string | If it is the link that is being long pressed, the original URL is returned.| | string | If it is a link that is being long pressed, the original URL is returned.|
### getSourceUrl<sup>9+</sup> ### getSourceUrl<sup>9+</sup>
...@@ -2322,7 +2719,7 @@ Sets the geolocation permission status of a web page. ...@@ -2322,7 +2719,7 @@ Sets the geolocation permission status of a web page.
| Name | Type| Mandatory| Default Value| Description | | Name | Type| Mandatory| Default Value| Description |
| --------- | ------- | ---- | ----- | ---------------------- | | --------- | ------- | ---- | ----- | ---------------------- |
| origin | string | Yes | - | Index of the source. | | origin | string | Yes | - | Index of the origin. |
| allow | boolean | Yes | - | Geolocation permission status.| | allow | boolean | Yes | - | Geolocation permission status.|
| retain | boolean | Yes | - | Whether the geolocation permission status can be saved to the system. The **[GeolocationPermissions](#geolocationpermissions9)** API can be used to manage the geolocation permission status saved to the system.| | retain | boolean | Yes | - | Whether the geolocation permission status can be saved to the system. The **[GeolocationPermissions](#geolocationpermissions9)** API can be used to manage the geolocation permission status saved to the system.|
...@@ -2349,13 +2746,13 @@ Requests focus for this web page. ...@@ -2349,13 +2746,13 @@ Requests focus for this web page.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('requestFocus') Button('requestFocus')
.onClick(() => { .onClick(() => {
this.controller.requestFocus(); this.controller.requestFocus()
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2382,14 +2779,14 @@ Checks whether going to the previous page can be performed on the current page. ...@@ -2382,14 +2779,14 @@ Checks whether going to the previous page can be performed on the current page.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('accessBackward') Button('accessBackward')
.onClick(() => { .onClick(() => {
let result = this.controller.accessBackward(); let result = this.controller.accessBackward()
console.log('result:' + result); console.log('result:' + result)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2416,14 +2813,14 @@ Checks whether going to the next page can be performed on the current page. ...@@ -2416,14 +2813,14 @@ Checks whether going to the next page can be performed on the current page.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('accessForward') Button('accessForward')
.onClick(() => { .onClick(() => {
let result = this.controller.accessForward(); let result = this.controller.accessForward()
console.log('result:' + result); console.log('result:' + result)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2435,19 +2832,19 @@ Checks whether going to the next page can be performed on the current page. ...@@ -2435,19 +2832,19 @@ Checks whether going to the next page can be performed on the current page.
accessStep(step: number): boolean accessStep(step: number): boolean
Indicates whether a specific number of steps forward or backward can be performed on the current page. Performs a specific number of steps forward or backward from the current page.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | --------------------- | | ---- | ------ | ---- | ---- | --------------------- |
| step | number | Yes | - | Number of the steps to take. A positive number means to going forward, and a negative number means to going backward.| | step | number | Yes | - | Number of the steps to take. A positive number means to go forward, and a negative number means to go backward.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | --------- | | ------- | --------- |
| boolean | Whether to go forward or backward from the current page.| | boolean | Whether going forward or backward from the current page is successful.|
**Example** **Example**
...@@ -2456,15 +2853,15 @@ Indicates whether a specific number of steps forward or backward can be performe ...@@ -2456,15 +2853,15 @@ Indicates whether a specific number of steps forward or backward can be performe
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
@State steps: number = 2; @State steps: number = 2
build() { build() {
Column() { Column() {
Button('accessStep') Button('accessStep')
.onClick(() => { .onClick(() => {
let result = this.controller.accessStep(this.steps); let result = this.controller.accessStep(this.steps)
console.log('result:' + result); console.log('result:' + result)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2485,13 +2882,13 @@ Goes to the previous page based on the history stack. This API is generally used ...@@ -2485,13 +2882,13 @@ Goes to the previous page based on the history stack. This API is generally used
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('backward') Button('backward')
.onClick(() => { .onClick(() => {
this.controller.backward(); this.controller.backward()
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2512,13 +2909,13 @@ Goes to the next page based on the history stack. This API is generally used tog ...@@ -2512,13 +2909,13 @@ Goes to the next page based on the history stack. This API is generally used tog
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('forward') Button('forward')
.onClick(() => { .onClick(() => {
this.controller.forward(); this.controller.forward()
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2545,14 +2942,14 @@ Performs a specific number of steps forward or backward on the current page base ...@@ -2545,14 +2942,14 @@ Performs a specific number of steps forward or backward on the current page base
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
@State step: number = -2; @State step: number = -2
build() { build() {
Column() { Column() {
Button('backOrForward') Button('backOrForward')
.onClick(() => { .onClick(() => {
this.controller.backOrForward(this.step); this.controller.backOrForward(this.step)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2579,14 +2976,14 @@ Deletes a specific application JavaScript object that is registered with the win ...@@ -2579,14 +2976,14 @@ Deletes a specific application JavaScript object that is registered with the win
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
@State name: string = 'Object'; @State name: string = 'Object'
build() { build() {
Column() { Column() {
Button('deleteJavaScriptRegister') Button('deleteJavaScriptRegister')
.onClick(() => { .onClick(() => {
this.controller.deleteJavaScriptRegister(this.name); this.controller.deleteJavaScriptRegister(this.name)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2613,14 +3010,14 @@ Obtains the element type of the area being clicked. ...@@ -2613,14 +3010,14 @@ Obtains the element type of the area being clicked.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('getHitTest') Button('getHitTest')
.onClick(() => { .onClick(() => {
let hitType = this.controller.getHitTest(); let hitType = this.controller.getHitTest()
console.log("hitType: " + hitType); console.log("hitType: " + hitType)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2646,15 +3043,15 @@ Obtains the element information of the area being clicked. ...@@ -2646,15 +3043,15 @@ Obtains the element information of the area being clicked.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('getHitTestValue') Button('getHitTestValue')
.onClick(() => { .onClick(() => {
let hitValue = this.controller.getHitTestValue(); let hitValue = this.controller.getHitTestValue()
console.log("hitType: " + hitValue.getType()); console.log("hitType: " + hitValue.getType())
console.log("extra: " + hitValue.getExtra()); console.log("extra: " + hitValue.getExtra())
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2680,14 +3077,14 @@ Obtains the index value of this **\<Web>** component, which can be used for **\< ...@@ -2680,14 +3077,14 @@ Obtains the index value of this **\<Web>** component, which can be used for **\<
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('getWebId') Button('getWebId')
.onClick(() => { .onClick(() => {
let id = this.controller.getWebId(); let id = this.controller.getWebId()
console.log("id: " + id); console.log("id: " + id)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2713,14 +3110,14 @@ Obtains the title of the current web page. ...@@ -2713,14 +3110,14 @@ Obtains the title of the current web page.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('getTitle') Button('getTitle')
.onClick(() => { .onClick(() => {
let title = this.controller.getTitle(); let title = this.controller.getTitle()
console.log("title: " + title); console.log("title: " + title)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2746,14 +3143,14 @@ Obtains the height of the current web page. ...@@ -2746,14 +3143,14 @@ Obtains the height of the current web page.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('getPageHeight') Button('getPageHeight')
.onClick(() => { .onClick(() => {
let pageHeight = this.controller.getPageHeight(); let pageHeight = this.controller.getPageHeight()
console.log("pageHeight: " + pageHeight); console.log("pageHeight: " + pageHeight)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2779,14 +3176,14 @@ Obtains the default user agent of the current web page. ...@@ -2779,14 +3176,14 @@ Obtains the default user agent of the current web page.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('getDefaultUserAgent') Button('getDefaultUserAgent')
.onClick(() => { .onClick(() => {
let userAgent = this.controller.getDefaultUserAgent(); let userAgent = this.controller.getDefaultUserAgent()
console.log("userAgent: " + userAgent); console.log("userAgent: " + userAgent)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2821,7 +3218,7 @@ If **baseUrl** is set to an HTTP or HTTPS URL, the encoded string will be proces ...@@ -2821,7 +3218,7 @@ If **baseUrl** is set to an HTTP or HTTPS URL, the encoded string will be proces
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
...@@ -2831,7 +3228,7 @@ If **baseUrl** is set to an HTTP or HTTPS URL, the encoded string will be proces ...@@ -2831,7 +3228,7 @@ If **baseUrl** is set to an HTTP or HTTPS URL, the encoded string will be proces
data: "<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>", data: "<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>",
mimeType: "text/html", mimeType: "text/html",
encoding: "UTF-8" encoding: "UTF-8"
}); })
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2863,13 +3260,13 @@ The object injected through **registerJavaScriptProxy** is still valid on a new ...@@ -2863,13 +3260,13 @@ The object injected through **registerJavaScriptProxy** is still valid on a new
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('loadUrl') Button('loadUrl')
.onClick(() => { .onClick(() => {
this.controller.loadUrl({ url: 'www.example.com' }); this.controller.loadUrl({ url: 'www.example.com' })
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2881,7 +3278,7 @@ The object injected through **registerJavaScriptProxy** is still valid on a new ...@@ -2881,7 +3278,7 @@ The object injected through **registerJavaScriptProxy** is still valid on a new
onActive(): void onActive(): void
Invoked to instruct the **\<Web>** component to enter the foreground, active state. Invoked when the **\<Web>** component enters the active state.
**Example** **Example**
...@@ -2890,13 +3287,13 @@ Invoked to instruct the **\<Web>** component to enter the foreground, active sta ...@@ -2890,13 +3287,13 @@ Invoked to instruct the **\<Web>** component to enter the foreground, active sta
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('onActive') Button('onActive')
.onClick(() => { .onClick(() => {
this.controller.onActive(); this.controller.onActive()
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2908,7 +3305,7 @@ Invoked to instruct the **\<Web>** component to enter the foreground, active sta ...@@ -2908,7 +3305,7 @@ Invoked to instruct the **\<Web>** component to enter the foreground, active sta
onInactive(): void onInactive(): void
Invoked to instruct the **\<Web>** component to enter the inactive state. Invoked when the **\<Web>** component enters the inactive state.
**Example** **Example**
...@@ -2917,13 +3314,13 @@ Invoked to instruct the **\<Web>** component to enter the inactive state. ...@@ -2917,13 +3314,13 @@ Invoked to instruct the **\<Web>** component to enter the inactive state.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('onInactive') Button('onInactive')
.onClick(() => { .onClick(() => {
this.controller.onInactive(); this.controller.onInactive()
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2949,14 +3346,14 @@ Sets a zoom factor for the current web page. ...@@ -2949,14 +3346,14 @@ Sets a zoom factor for the current web page.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
@State factor: number = 1; @State factor: number = 1
build() { build() {
Column() { Column() {
Button('zoom') Button('zoom')
.onClick(() => { .onClick(() => {
this.controller.zoom(this.factor); this.controller.zoom(this.factor)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2982,14 +3379,14 @@ Zooms in on the current web page by 20%. ...@@ -2982,14 +3379,14 @@ Zooms in on the current web page by 20%.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('zoomIn') Button('zoomIn')
.onClick(() => { .onClick(() => {
let result = this.controller.zoomIn(); let result = this.controller.zoomIn()
console.log("result: " + result); console.log("result: " + result)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -3000,7 +3397,7 @@ Zooms in on the current web page by 20%. ...@@ -3000,7 +3397,7 @@ Zooms in on the current web page by 20%.
### zoomOut<sup>9+</sup> ### zoomOut<sup>9+</sup>
zoomOut(): boolean zoomOut(): boolean
Zooms out the current web page by 20%. Zooms out of the current web page by 20%.
**Return value** **Return value**
...@@ -3015,14 +3412,14 @@ Zooms out the current web page by 20%. ...@@ -3015,14 +3412,14 @@ Zooms out the current web page by 20%.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('zoomOut') Button('zoomOut')
.onClick(() => { .onClick(() => {
let result = this.controller.zoomOut(); let result = this.controller.zoomOut()
console.log("result: " + result); console.log("result: " + result)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -3034,7 +3431,7 @@ Zooms out the current web page by 20%. ...@@ -3034,7 +3431,7 @@ Zooms out the current web page by 20%.
refresh() refresh()
Invoked to instruct the **\<Web>** component to refresh the web page. Invoked when the **\<Web>** component refreshes the web page.
**Example** **Example**
...@@ -3043,13 +3440,13 @@ Invoked to instruct the **\<Web>** component to refresh the web page. ...@@ -3043,13 +3440,13 @@ Invoked to instruct the **\<Web>** component to refresh the web page.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('refresh') Button('refresh')
.onClick(() => { .onClick(() => {
this.controller.refresh(); this.controller.refresh()
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -3067,7 +3464,7 @@ Registers a JavaScript object and invokes the methods of the object in the windo ...@@ -3067,7 +3464,7 @@ Registers a JavaScript object and invokes the methods of the object in the windo
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ---------- | --------------- | ---- | ---- | ---------------------------------------- | | ---------- | --------------- | ---- | ---- | ---------------------------------------- |
| object | object | Yes | - | Application-side JavaScript object to be registered. Methods can be declared, but not attributes. The parameters and return value can only be of the string, number, or Boolean type.| | object | object | Yes | - | Application-side JavaScript object to be registered. Methods can be declared, but attributes cannot. The parameters and return value can only be of the string, number, or Boolean type.|
| name | string | Yes | - | Name of the object to be registered, which is the same as that invoked in the window. After registration, the window can use this name to access the JavaScript object at the application side.| | name | string | Yes | - | Name of the object to be registered, which is the same as that invoked in the window. After registration, the window can use this name to access the JavaScript object at the application side.|
| methodList | Array\<string\> | Yes | - | Methods of the JavaScript object to be registered at the application side. | | methodList | Array\<string\> | Yes | - | Methods of the JavaScript object to be registered at the application side. |
...@@ -3081,10 +3478,10 @@ Registers a JavaScript object and invokes the methods of the object in the windo ...@@ -3081,10 +3478,10 @@ Registers a JavaScript object and invokes the methods of the object in the windo
controller: WebController = new WebController() controller: WebController = new WebController()
testObj = { testObj = {
test: (data) => { test: (data) => {
return "ArkUI Web Component"; return "ArkUI Web Component"
}, },
toString: () => { toString: () => {
console.log('Web Component toString'); console.log('Web Component toString')
} }
} }
build() { build() {
...@@ -3095,7 +3492,7 @@ Registers a JavaScript object and invokes the methods of the object in the windo ...@@ -3095,7 +3492,7 @@ Registers a JavaScript object and invokes the methods of the object in the windo
object: this.testObj, object: this.testObj,
name: "objName", name: "objName",
methodList: ["test", "toString"], methodList: ["test", "toString"],
}); })
}) })
} }
Web({ src: $rawfile('index.html'), controller: this.controller }) Web({ src: $rawfile('index.html'), controller: this.controller })
...@@ -3115,8 +3512,8 @@ Registers a JavaScript object and invokes the methods of the object in the windo ...@@ -3115,8 +3512,8 @@ Registers a JavaScript object and invokes the methods of the object in the windo
</body> </body>
<script type="text/javascript"> <script type="text/javascript">
function htmlTest() { function htmlTest() {
str = objName.test("test function"); str = objName.test("test function")
console.log('objName.test result:'+ str); console.log('objName.test result:'+ str)
} }
</script> </script>
</html> </html>
...@@ -3143,7 +3540,7 @@ Asynchronously executes a JavaScript script. This API uses a callback to return ...@@ -3143,7 +3540,7 @@ Asynchronously executes a JavaScript script. This API uses a callback to return
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
@State webResult: string = '' @State webResult: string = ''
build() { build() {
Column() { Column() {
...@@ -3156,8 +3553,8 @@ Asynchronously executes a JavaScript script. This API uses a callback to return ...@@ -3156,8 +3553,8 @@ Asynchronously executes a JavaScript script. This API uses a callback to return
callback: (result: string)=> { callback: (result: string)=> {
this.webResult = result this.webResult = result
console.info(`The test() return value is: ${result}`) console.info(`The test() return value is: ${result}`)
}}); }})
console.info('url: ', e.url); console.info('url: ', e.url)
}) })
} }
} }
...@@ -3174,7 +3571,7 @@ Asynchronously executes a JavaScript script. This API uses a callback to return ...@@ -3174,7 +3571,7 @@ Asynchronously executes a JavaScript script. This API uses a callback to return
</body> </body>
<script type="text/javascript"> <script type="text/javascript">
function test() { function test() {
console.log('Ark WebComponent'); console.log('Ark WebComponent')
return "This value is from index.html" return "This value is from index.html"
} }
</script> </script>
...@@ -3195,13 +3592,13 @@ Stops page loading. ...@@ -3195,13 +3592,13 @@ Stops page loading.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('stop') Button('stop')
.onClick(() => { .onClick(() => {
this.controller.stop(); this.controller.stop()
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -3222,13 +3619,13 @@ Clears the browsing history. ...@@ -3222,13 +3619,13 @@ Clears the browsing history.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('clearHistory') Button('clearHistory')
.onClick(() => { .onClick(() => {
this.controller.clearHistory(); this.controller.clearHistory()
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -3240,7 +3637,7 @@ Clears the browsing history. ...@@ -3240,7 +3637,7 @@ Clears the browsing history.
clearSslCache(): void clearSslCache(): void
Clears user operation corresponding to the SSL certificate error event recorded by the web component. Clears the user operation corresponding to the SSL certificate error event recorded by the **\<Web>** component.
**Example** **Example**
...@@ -3249,13 +3646,13 @@ Clears user operation corresponding to the SSL certificate error event recorded ...@@ -3249,13 +3646,13 @@ Clears user operation corresponding to the SSL certificate error event recorded
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('clearSslCache') Button('clearSslCache')
.onClick(() => { .onClick(() => {
this.controller.clearSslCache(); this.controller.clearSslCache()
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -3267,7 +3664,7 @@ Clears user operation corresponding to the SSL certificate error event recorded ...@@ -3267,7 +3664,7 @@ Clears user operation corresponding to the SSL certificate error event recorded
clearClientAuthenticationCache(): void clearClientAuthenticationCache(): void
Clears the user operation corresponding to the client certificate request event recorded by the web component. Clears the user operation corresponding to the client certificate request event recorded by the \<Web> component.
**Example** **Example**
...@@ -3276,13 +3673,13 @@ Clears the user operation corresponding to the client certificate request event ...@@ -3276,13 +3673,13 @@ Clears the user operation corresponding to the client certificate request event
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('clearClientAuthenticationCache') Button('clearClientAuthenticationCache')
.onClick(() => { .onClick(() => {
this.controller.clearClientAuthenticationCache(); this.controller.clearClientAuthenticationCache()
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -3309,13 +3706,13 @@ Obtains the cookie management object of the **\<Web>** component. ...@@ -3309,13 +3706,13 @@ Obtains the cookie management object of the **\<Web>** component.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('getCookieManager') Button('getCookieManager')
.onClick(() => { .onClick(() => {
let cookieManager = this.controller.getCookieManager(); let cookieManager = this.controller.getCookieManager()
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -3334,7 +3731,7 @@ Creates web message ports. ...@@ -3334,7 +3731,7 @@ Creates web message ports.
| Type | Description | | Type | Description |
| ------------------------------- | ------------- | | ------------------------------- | ------------- |
| Array\<[WebMessagePort](#webmessageport9)\> | Array of web message ports.| | Array\<[WebMessagePort](#webmessageport9)\> | List of web message ports.|
**Example** **Example**
...@@ -3343,13 +3740,13 @@ Creates web message ports. ...@@ -3343,13 +3740,13 @@ Creates web message ports.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
ports: WebMessagePort[] = null; ports: WebMessagePort[] = null
build() { build() {
Column() { Column() {
Button('createWebMessagePorts') Button('createWebMessagePorts')
.onClick(() => { .onClick(() => {
this.ports = this.controller.createWebMessagePorts(); this.ports = this.controller.createWebMessagePorts()
console.log("createWebMessagePorts size:" + this.ports.length) console.log("createWebMessagePorts size:" + this.ports.length)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -3362,50 +3759,111 @@ Creates web message ports. ...@@ -3362,50 +3759,111 @@ Creates web message ports.
postMessage(options: { message: WebMessageEvent, uri: string}): void postMessage(options: { message: WebMessageEvent, uri: string}): void
Sends a web message to an HTML5 page. Sends a web message to an HTML5 window.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ---------- | --------------- | ---- | ---- | ------------------------- | | ---------- | --------------- | ---- | ---- | ------------------------- |
| message | [WebMessageEvent](#webmessageevent9) | Yes | - |Message to send, including data and the message port.| | message | [WebMessageEvent](#webmessageevent9) | Yes | - |Message to send, including the data and message port.|
| uri | string | Yes | - | URI to receive the message.| | uri | string | Yes | - | URI for receiving the message.|
**Example** **Example**
```ts ```ts
// xxx.ets // index.ets
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
ports: WebMessagePort[] = null; ports: WebMessagePort[] = null
@State sendFromEts: string = 'Send this message from ets to HTML'
@State receivedFromHtml: string = 'Display received message send from HTML'
build() { build() {
Column() { Column() {
Button('postMessage') // Display the received HTML content.
Text(this.receivedFromHtml)
// Send the content in the text box to an HTML window.
TextInput({placeholder: 'Send this message from ets to HTML'})
.onChange((value: string) => {
this.sendFromEts = value
})
// 1. Create two message ports.
Button('1.CreateWebMessagePorts')
.onClick(() => { .onClick(() => {
var sendPortArray = new Array(this.ports[1]); this.ports = this.controller.createWebMessagePorts()
var msgEvent = new WebMessageEvent(); console.log("createWebMessagePorts size:" + this.ports.length)
msgEvent.setData("__init_ports__");
msgEvent.setPorts(sendPortArray);
this.controller.postMessage({message: msgEvent, uri: "*"});
}) })
Web({ src: 'www.example.com', controller: this.controller })
// 2. Send one of the message ports to the HTML side, which can then save and use the port.
Button('2.PostMessagePort')
.onClick(() => {
var sendPortArray = new Array(this.ports[1])
var msgEvent = new WebMessageEvent()
msgEvent.setData("__init_port__")
msgEvent.setPorts(sendPortArray)
this.controller.postMessage({message: msgEvent, uri: "*"})
})
// 3. Register a callback for the other message port on the application side.
Button('3.RegisterCallback')
.onClick(() => {
this.ports[0].onMessageEvent((result: string) => {
var msg = 'Got msg from HTML: ' + result
this.receivedFromHtml = msg
})
})
// 4. Use the port on the application side to send messages to the message port that has been sent to the HTML.
Button('4.SendDataToHtml5')
.onClick(() => {
var msg = new WebMessageEvent()
msg.setData(this.sendFromEts)
this.ports[0].postMessageEvent(msg)
})
Web({ src: $rawfile("index.html"), controller: this.controller })
.javaScriptAccess(true)
.fileAccess(true)
} }
} }
} }
// xxx.js
// index.html
<!DOCTYPE html>
<html>
<body>
<h1>Web Message Port Demo</h1>
<div style="font-size: 24pt;">
<input type="button" value="5.SendToEts" onclick="PostMsgToEts(msgFromJS.value);" /><br/>
<input id="msgFromJS" type="text" value="send this message from HTML to ets" style="font-size: 16pt;" /><br/>
</div>
<p class="output">display received message send from ets</p>
</body>
<script src="index.js"></script>
</html>
// index.js
var h5Port; var h5Port;
window.addEventListener('message', function(event){ var output = document.querySelector('.output');
if (event.data == '__init_ports__') { window.addEventListener('message', function(event) {
if (event.data == '__init_port__') {
if(event.ports[0] != null) { if(event.ports[0] != null) {
h5Port = event.ports[0]; h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side.
h5Port.onmessage = function(event) { h5Port.onmessage = function(event) {
console.log('receive message from ets, on message:' + event.data); // 2. Receive the message sent from the eTS side.
var msg = 'Got message from ets:' + event.data;
output.innerHTML = msg;
} }
} }
} }
}) })
// 3. Use h5Port to send messages to the eTS side.
function PostMsgToEts(data) {
h5Port.postMessage(data)
}
``` ```
### getUrl<sup>9+</sup> ### getUrl<sup>9+</sup>
...@@ -3427,12 +3885,12 @@ Obtains the URL of the current page. ...@@ -3427,12 +3885,12 @@ Obtains the URL of the current page.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('getUrl') Button('getUrl')
.onClick(() => { .onClick(() => {
console.log("url: " + this.controller.getUrl()); console.log("url: " + this.controller.getUrl())
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -3495,14 +3953,14 @@ Sets the cookie. This API returns the result synchronously. Returns **true** if ...@@ -3495,14 +3953,14 @@ Sets the cookie. This API returns the result synchronously. Returns **true** if
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('setCookie') Button('setCookie')
.onClick(() => { .onClick(() => {
let result = this.controller.getCookieManager().setCookie("www.example.com", "a=b"); let result = this.controller.getCookieManager().setCookie("www.example.com", "a=b")
console.log("result: " + result); console.log("result: " + result)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -3513,7 +3971,7 @@ Sets the cookie. This API returns the result synchronously. Returns **true** if ...@@ -3513,7 +3971,7 @@ Sets the cookie. This API returns the result synchronously. Returns **true** if
### saveCookieSync<sup>9+</sup> ### saveCookieSync<sup>9+</sup>
saveCookieSync(): boolean saveCookieSync(): boolean
Saves this cookie in the memory to the drive. This API returns the result synchronously. Saves the cookies in the memory to the drive. This API returns the result synchronously.
**Return value** **Return value**
...@@ -3528,14 +3986,14 @@ Saves this cookie in the memory to the drive. This API returns the result synchr ...@@ -3528,14 +3986,14 @@ Saves this cookie in the memory to the drive. This API returns the result synchr
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('saveCookieSync') Button('saveCookieSync')
.onClick(() => { .onClick(() => {
let result = this.controller.getCookieManager().saveCookieSync(); let result = this.controller.getCookieManager().saveCookieSync()
console.log("result: " + result); console.log("result: " + result)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -3568,14 +4026,14 @@ Obtains the cookie value corresponding to the specified URL. ...@@ -3568,14 +4026,14 @@ Obtains the cookie value corresponding to the specified URL.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('getCookie') Button('getCookie')
.onClick(() => { .onClick(() => {
let value = webview.WebCookieManager.getCookie('www.example.com'); let value = webview.WebCookieManager.getCookie('www.example.com')
console.log("value: " + value); console.log("value: " + value)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -3609,14 +4067,14 @@ Sets a cookie value for the specified URL. ...@@ -3609,14 +4067,14 @@ Sets a cookie value for the specified URL.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('setCookie') Button('setCookie')
.onClick(() => { .onClick(() => {
let result = web_webview.WebCookieManager.setCookie('www.example.com', 'a=b'); let result = web_webview.WebCookieManager.setCookie('www.example.com', 'a=b')
console.log("result: " + result); console.log("result: " + result)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -3627,7 +4085,7 @@ Sets a cookie value for the specified URL. ...@@ -3627,7 +4085,7 @@ Sets a cookie value for the specified URL.
### saveCookieSync<sup>9+</sup> ### saveCookieSync<sup>9+</sup>
saveCookieSync(): boolean saveCookieSync(): boolean
Saves cookies in the memory to the drive. This API is synchronous. Saves the cookies in the memory to the drive. This API returns the result synchronously.
**Return value** **Return value**
...@@ -3643,14 +4101,14 @@ Saves cookies in the memory to the drive. This API is synchronous. ...@@ -3643,14 +4101,14 @@ Saves cookies in the memory to the drive. This API is synchronous.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('saveCookieSync') Button('saveCookieSync')
.onClick(() => { .onClick(() => {
let result = web_webview.WebCookieManager.saveCookieSync(); let result = web_webview.WebCookieManager.saveCookieSync()
console.log("result: " + result); console.log("result: " + result)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -3677,7 +4135,7 @@ Saves cookies in the memory to the drive. This API uses a promise to return the ...@@ -3677,7 +4135,7 @@ Saves cookies in the memory to the drive. This API uses a promise to return the
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
...@@ -3685,11 +4143,11 @@ Saves cookies in the memory to the drive. This API uses a promise to return the ...@@ -3685,11 +4143,11 @@ Saves cookies in the memory to the drive. This API uses a promise to return the
.onClick(() => { .onClick(() => {
web_webview.WebCookieManager.saveCookieAsync() web_webview.WebCookieManager.saveCookieAsync()
.then (function(result) { .then (function(result) {
console.log("result: " + result); console.log("result: " + result)
}) })
.catch(function(error) { .catch(function(error) {
console.error("error: " + error); console.error("error: " + error)
}); })
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -3700,7 +4158,7 @@ Saves cookies in the memory to the drive. This API uses a promise to return the ...@@ -3700,7 +4158,7 @@ Saves cookies in the memory to the drive. This API uses a promise to return the
### saveCookieAsync<sup>9+</sup> ### saveCookieAsync<sup>9+</sup>
saveCookieAsync(callback: AsyncCallback\<boolean>): void saveCookieAsync(callback: AsyncCallback\<boolean>): void
Saves cookies in the memory to the drive. This API uses an asynchronous callback to return the value. Saves cookies in the memory to the drive. This API uses an asynchronous callback to return the result.
**Parameters** **Parameters**
...@@ -3716,15 +4174,15 @@ Saves cookies in the memory to the drive. This API uses an asynchronous callback ...@@ -3716,15 +4174,15 @@ Saves cookies in the memory to the drive. This API uses an asynchronous callback
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('saveCookieAsync') Button('saveCookieAsync')
.onClick(() => { .onClick(() => {
web_webview.WebCookieManager.saveCookieAsync(function(result) { web_webview.WebCookieManager.saveCookieAsync(function(result) {
console.log("result: " + result); console.log("result: " + result)
}); })
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -3751,14 +4209,14 @@ Checks whether the **WebCookieManager** instance has the permission to send and ...@@ -3751,14 +4209,14 @@ Checks whether the **WebCookieManager** instance has the permission to send and
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('isCookieAllowed') Button('isCookieAllowed')
.onClick(() => { .onClick(() => {
let result = web_webview.WebCookieManager.isCookieAllowed(); let result = web_webview.WebCookieManager.isCookieAllowed()
console.log("result: " + result); console.log("result: " + result)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -3785,13 +4243,13 @@ Sets whether the **WebCookieManager** instance has the permission to send and re ...@@ -3785,13 +4243,13 @@ Sets whether the **WebCookieManager** instance has the permission to send and re
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('putAcceptCookieEnabled') Button('putAcceptCookieEnabled')
.onClick(() => { .onClick(() => {
web_webview.WebCookieManager.putAcceptCookieEnabled(false); web_webview.WebCookieManager.putAcceptCookieEnabled(false)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -3818,14 +4276,14 @@ Checks whether the **WebCookieManager** instance has the permission to send and ...@@ -3818,14 +4276,14 @@ Checks whether the **WebCookieManager** instance has the permission to send and
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('isThirdPartyCookieAllowed') Button('isThirdPartyCookieAllowed')
.onClick(() => { .onClick(() => {
let result = web_webview.WebCookieManager.isThirdPartyCookieAllowed(); let result = web_webview.WebCookieManager.isThirdPartyCookieAllowed()
console.log("result: " + result); console.log("result: " + result)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -3852,13 +4310,13 @@ Sets whether the **WebCookieManager** instance has the permission to send and re ...@@ -3852,13 +4310,13 @@ Sets whether the **WebCookieManager** instance has the permission to send and re
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('putAcceptThirdPartyCookieEnabled') Button('putAcceptThirdPartyCookieEnabled')
.onClick(() => { .onClick(() => {
web_webview.WebCookieManager.putAcceptThirdPartyCookieEnabled(false); web_webview.WebCookieManager.putAcceptThirdPartyCookieEnabled(false)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -3885,14 +4343,14 @@ Checks whether cookies exist. ...@@ -3885,14 +4343,14 @@ Checks whether cookies exist.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('existCookie') Button('existCookie')
.onClick(() => { .onClick(() => {
let result = web_webview.WebCookieManager.existCookie(); let result = web_webview.WebCookieManager.existCookie()
console.log("result: " + result); console.log("result: " + result)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -3913,13 +4371,13 @@ Deletes all cookies. ...@@ -3913,13 +4371,13 @@ Deletes all cookies.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('deleteEntireCookie') Button('deleteEntireCookie')
.onClick(() => { .onClick(() => {
web_webview.WebCookieManager.deleteEntireCookie(); web_webview.WebCookieManager.deleteEntireCookie()
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -3940,13 +4398,13 @@ Deletes all session cookies. ...@@ -3940,13 +4398,13 @@ Deletes all session cookies.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('deleteSessionCookie') Button('deleteSessionCookie')
.onClick(() => { .onClick(() => {
webview.WebCookieManager.deleteSessionCookie(); webview.WebCookieManager.deleteSessionCookie()
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -3977,14 +4435,14 @@ Checks whether any saved HTTP authentication credentials exist. This API is sync ...@@ -3977,14 +4435,14 @@ Checks whether any saved HTTP authentication credentials exist. This API is sync
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('existHttpAuthCredentials') Button('existHttpAuthCredentials')
.onClick(() => { .onClick(() => {
let result = web_webview.WebDataBase.existHttpAuthCredentials(); let result = web_webview.WebDataBase.existHttpAuthCredentials()
console.log('result: ' + result); console.log('result: ' + result)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -4006,13 +4464,13 @@ Deletes all HTTP authentication credentials saved in the cache. This API returns ...@@ -4006,13 +4464,13 @@ Deletes all HTTP authentication credentials saved in the cache. This API returns
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('deleteHttpAuthCredentials') Button('deleteHttpAuthCredentials')
.onClick(() => { .onClick(() => {
web_webview.WebDataBase.deleteHttpAuthCredentials(); web_webview.WebDataBase.deleteHttpAuthCredentials()
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -4047,18 +4505,18 @@ Retrieves HTTP authentication credentials for a given host and domain. This API ...@@ -4047,18 +4505,18 @@ Retrieves HTTP authentication credentials for a given host and domain. This API
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
host: string = "www.spincast.org"; host: string = "www.spincast.org"
realm: string = "protected example"; realm: string = "protected example"
username_password: string[]; username_password: string[]
build() { build() {
Column() { Column() {
Button('getHttpAuthCredentials') Button('getHttpAuthCredentials')
.onClick(() => { .onClick(() => {
this.username_password = web_webview.WebDataBase.getHttpAuthCredentials(this.host, this.realm); this.username_password = web_webview.WebDataBase.getHttpAuthCredentials(this.host, this.realm)
console.log('num: ' + this.username_password.length); console.log('num: ' + this.username_password.length)
ForEach(this.username_password, (item) => { ForEach(this.username_password, (item) => {
console.log('username_password: ' + item); console.log('username_password: ' + item)
}, item => item) }, item => item)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -4090,14 +4548,14 @@ Saves HTTP authentication credentials for a given host and realm. This API retur ...@@ -4090,14 +4548,14 @@ Saves HTTP authentication credentials for a given host and realm. This API retur
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
host: string = "www.spincast.org"; host: string = "www.spincast.org"
realm: string = "protected example"; realm: string = "protected example"
build() { build() {
Column() { Column() {
Button('saveHttpAuthCredentials') Button('saveHttpAuthCredentials')
.onClick(() => { .onClick(() => {
web_webview.WebDataBase.saveHttpAuthCredentials(this.host, this.realm, "Stromgol", "Laroche"); web_webview.WebDataBase.saveHttpAuthCredentials(this.host, this.realm, "Stromgol", "Laroche")
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -4119,23 +4577,23 @@ Allows the specified source to use the geolocation information. ...@@ -4119,23 +4577,23 @@ Allows the specified source to use the geolocation information.
| Name | Type| Mandatory| Default Value| Description | | Name | Type| Mandatory| Default Value| Description |
| -------- | -------- | ---- | ----- | ------------- | | -------- | -------- | ---- | ----- | ------------- |
| origin | string | Yes | - | Index of the source.| | origin | string | Yes | - | Index of the origin.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
import web_webview from '@ohos.web.webview'; import web_webview from '@ohos.web.webview'
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
origin: string = "file:///"; origin: string = "file:///"
build() { build() {
Column() { Column() {
Button('allowGeolocation') Button('allowGeolocation')
.onClick(() => { .onClick(() => {
web_webview.GeolocationPermissions.allowGeolocation(this.origin); web_webview.GeolocationPermissions.allowGeolocation(this.origin)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -4153,23 +4611,23 @@ Clears the geolocation permission status of a specified source. ...@@ -4153,23 +4611,23 @@ Clears the geolocation permission status of a specified source.
| Name | Type| Mandatory| Default Value| Description | | Name | Type| Mandatory| Default Value| Description |
| -------- | -------- | ---- | ----- | ------------- | | -------- | -------- | ---- | ----- | ------------- |
| origin | string | Yes | - | Index of the source.| | origin | string | Yes | - | Index of the origin.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
import web_webview from '@ohos.web.webview'; import web_webview from '@ohos.web.webview'
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
origin: string = "file:///"; origin: string = "file:///"
build() { build() {
Column() { Column() {
Button('deleteGeolocation') Button('deleteGeolocation')
.onClick(() => { .onClick(() => {
web_webview.GeolocationPermissions.deleteGeolocation(this.origin); web_webview.GeolocationPermissions.deleteGeolocation(this.origin)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -4187,16 +4645,16 @@ Clears the geolocation permission status of all sources. ...@@ -4187,16 +4645,16 @@ Clears the geolocation permission status of all sources.
```ts ```ts
// xxx.ets // xxx.ets
import web_webview from '@ohos.web.webview'; import web_webview from '@ohos.web.webview'
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('deleteAllGeolocation') Button('deleteAllGeolocation')
.onClick(() => { .onClick(() => {
web_webview.GeolocationPermissions.deleteAllGeolocation(); web_webview.GeolocationPermissions.deleteAllGeolocation()
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -4221,23 +4679,23 @@ Obtains the geolocation permission status of the specified source. This API uses ...@@ -4221,23 +4679,23 @@ Obtains the geolocation permission status of the specified source. This API uses
```ts ```ts
// xxx.ets // xxx.ets
import web_webview from '@ohos.web.webview'; import web_webview from '@ohos.web.webview'
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
origin: string = "file:///"; origin: string = "file:///"
build() { build() {
Column() { Column() {
Button('getAccessibleGeolocationAsync') Button('getAccessibleGeolocationAsync')
.onClick(() => { .onClick(() => {
web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin, (error, result) => { web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin, (error, result) => {
if (error) { if (error) {
console.log('getAccessibleGeolocationAsync error: ' + JSON.stringify(error)); console.log('getAccessibleGeolocationAsync error: ' + JSON.stringify(error))
return; return
} }
console.log('getAccessibleGeolocationAsync result: ' + result); console.log('getAccessibleGeolocationAsync result: ' + result)
}); })
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -4267,21 +4725,21 @@ Obtains the geolocation permission status of the specified source. This API uses ...@@ -4267,21 +4725,21 @@ Obtains the geolocation permission status of the specified source. This API uses
```ts ```ts
// xxx.ets // xxx.ets
import web_webview from '@ohos.web.webview'; import web_webview from '@ohos.web.webview'
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
origin: string = "file:///"; origin: string = "file:///"
build() { build() {
Column() { Column() {
Button('getAccessibleGeolocationPromise') Button('getAccessibleGeolocationPromise')
.onClick(() => { .onClick(() => {
web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin).then(result => { web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin).then(result => {
console.log('getAccessibleGeolocationPromise result: ' + result); console.log('getAccessibleGeolocationPromise result: ' + result)
}).catch(error => { }).catch(error => {
console.log('getAccessibleGeolocationPromise error: ' + JSON.stringify(error)); console.log('getAccessibleGeolocationPromise error: ' + JSON.stringify(error))
}); })
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -4305,23 +4763,23 @@ Obtains the geolocation permission status of all sources. This API uses an async ...@@ -4305,23 +4763,23 @@ Obtains the geolocation permission status of all sources. This API uses an async
```ts ```ts
// xxx.ets // xxx.ets
import web_webview from '@ohos.web.webview'; import web_webview from '@ohos.web.webview'
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('getStoredGeolocationAsync') Button('getStoredGeolocationAsync')
.onClick(() => { .onClick(() => {
web_webview.GeolocationPermissions.getStoredGeolocation((error, origins) => { web_webview.GeolocationPermissions.getStoredGeolocation((error, origins) => {
if (error) { if (error) {
console.log('getStoredGeolocationAsync error: ' + JSON.stringify(error)); console.log('getStoredGeolocationAsync error: ' + JSON.stringify(error))
return; return
} }
let origins_str: string = origins.join(); let origins_str: string = origins.join()
console.log('getStoredGeolocationAsync origins: ' + origins_str); console.log('getStoredGeolocationAsync origins: ' + origins_str)
}); })
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -4351,21 +4809,21 @@ Obtains the geolocation permission status of all sources. This API uses a promis ...@@ -4351,21 +4809,21 @@ Obtains the geolocation permission status of all sources. This API uses a promis
```ts ```ts
// xxx.ets // xxx.ets
import web_webview from '@ohos.web.webview'; import web_webview from '@ohos.web.webview'
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('getStoredGeolocationPromise') Button('getStoredGeolocationPromise')
.onClick(() => { .onClick(() => {
web_webview.GeolocationPermissions.getStoredGeolocation().then(origins => { web_webview.GeolocationPermissions.getStoredGeolocation().then(origins => {
let origins_str: string = origins.join(); let origins_str: string = origins.join()
console.log('getStoredGeolocationPromise origins: ' + origins_str); console.log('getStoredGeolocationPromise origins: ' + origins_str)
}).catch(error => { }).catch(error => {
console.log('getStoredGeolocationPromise error: ' + JSON.stringify(error)); console.log('getStoredGeolocationPromise error: ' + JSON.stringify(error))
}); })
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -4388,12 +4846,12 @@ Deletes all data in the Web SQL database. ...@@ -4388,12 +4846,12 @@ Deletes all data in the Web SQL database.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('deleteAllData') Button('deleteAllData')
.onClick(() => { .onClick(() => {
web_webview.WebStorage.deleteAllData(); web_webview.WebStorage.deleteAllData()
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.databaseAccess(true) .databaseAccess(true)
...@@ -4421,13 +4879,13 @@ Deletes all data in the specified origin. ...@@ -4421,13 +4879,13 @@ Deletes all data in the specified origin.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
origin: string = "origin"; origin: string = "origin"
build() { build() {
Column() { Column() {
Button('getHttpAuthCredentials') Button('getHttpAuthCredentials')
.onClick(() => { .onClick(() => {
web_webview.WebStorage.deleteOrigin(this.origin); web_webview.WebStorage.deleteOrigin(this.origin)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.databaseAccess(true) .databaseAccess(true)
...@@ -4437,7 +4895,7 @@ Deletes all data in the specified origin. ...@@ -4437,7 +4895,7 @@ Deletes all data in the specified origin.
``` ```
### getOrigins<sup>9+</sup> ### getOrigins<sup>9+</sup>
static getOrigins(callback: AsyncCallback<Array<WebStorageOrigin>>) : void static getOrigins(callback: AsyncCallback\<Array\<WebStorageOrigin>>) : void
Obtains information about all origins that are currently using the Web SQL database. This API uses an asynchronous callback to return the result. Obtains information about all origins that are currently using the Web SQL database. This API uses an asynchronous callback to return the result.
...@@ -4455,21 +4913,21 @@ Obtains information about all origins that are currently using the Web SQL datab ...@@ -4455,21 +4913,21 @@ Obtains information about all origins that are currently using the Web SQL datab
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
origin: string = "origin"; origin: string = "origin"
build() { build() {
Column() { Column() {
Button('getOrigins') Button('getOrigins')
.onClick(() => { .onClick(() => {
web_webview.WebStorage.getOrigins((error, origins) => { web_webview.WebStorage.getOrigins((error, origins) => {
if (error) { if (error) {
console.log('error: ' + error); console.log('error: ' + error)
return; return
} }
for (let i = 0; i < origins.length; i++) { for (let i = 0; i < origins.length; i++) {
console.log('origin: ' + origins[i].origin); console.log('origin: ' + origins[i].origin)
console.log('usage: ' + origins[i].usage); console.log('usage: ' + origins[i].usage)
console.log('quota: ' + origins[i].quota); console.log('quota: ' + origins[i].quota)
} }
}) })
}) })
...@@ -4481,7 +4939,7 @@ Obtains information about all origins that are currently using the Web SQL datab ...@@ -4481,7 +4939,7 @@ Obtains information about all origins that are currently using the Web SQL datab
``` ```
### getOrigins<sup>9+</sup> ### getOrigins<sup>9+</sup>
static getOrigins() : Promise<Array<WebStorageOrigin>> static getOrigins() : Promise\<Array\<WebStorageOrigin>>
Obtains information about all origins that are currently using the Web SQL database. This API uses a promise to return the result. Obtains information about all origins that are currently using the Web SQL database. This API uses a promise to return the result.
...@@ -4499,8 +4957,8 @@ Obtains information about all origins that are currently using the Web SQL datab ...@@ -4499,8 +4957,8 @@ Obtains information about all origins that are currently using the Web SQL datab
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
origin: string = "origin"; origin: string = "origin"
build() { build() {
Column() { Column() {
Button('getOrigins') Button('getOrigins')
...@@ -4508,13 +4966,13 @@ Obtains information about all origins that are currently using the Web SQL datab ...@@ -4508,13 +4966,13 @@ Obtains information about all origins that are currently using the Web SQL datab
web_webview.WebStorage.getOrigins() web_webview.WebStorage.getOrigins()
.then(origins => { .then(origins => {
for (let i = 0; i < origins.length; i++) { for (let i = 0; i < origins.length; i++) {
console.log('origin: ' + origins[i].origin); console.log('origin: ' + origins[i].origin)
console.log('usage: ' + origins[i].usage); console.log('usage: ' + origins[i].usage)
console.log('quota: ' + origins[i].quota); console.log('quota: ' + origins[i].quota)
} }
}) })
.catch(error => { .catch(error => {
console.log('error: ' + error); console.log('error: ' + error)
}) })
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -4544,18 +5002,18 @@ Obtains the storage quota of an origin in the Web SQL database, in bytes. This A ...@@ -4544,18 +5002,18 @@ Obtains the storage quota of an origin in the Web SQL database, in bytes. This A
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
origin: string = "origin"; origin: string = "origin"
build() { build() {
Column() { Column() {
Button('getOriginQuota') Button('getOriginQuota')
.onClick(() => { .onClick(() => {
web_webview.WebStorage.getOriginQuota(this.origin, (error, quota) => { web_webview.WebStorage.getOriginQuota(this.origin, (error, quota) => {
if (error) { if (error) {
console.log('error: ' + error); console.log('error: ' + error)
return; return
} }
console.log('quota: ' + quota); console.log('quota: ' + quota)
}) })
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -4591,17 +5049,17 @@ Obtains the storage quota of an origin in the Web SQL database, in bytes. This A ...@@ -4591,17 +5049,17 @@ Obtains the storage quota of an origin in the Web SQL database, in bytes. This A
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController();
origin: string = "origin"; origin: string = "origin"
build() { build() {
Column() { Column() {
Button('getOriginQuota') Button('getOriginQuota')
.onClick(() => { .onClick(() => {
web_webview.WebStorage.getOriginQuota(this.origin) web_webview.WebStorage.getOriginQuota(this.origin)
.then(quota => { .then(quota => {
console.log('quota: ' + quota); console.log('quota: ' + quota)
}) })
.catch(error => { .catch(error => {
console.log('error: ' + error); console.log('error: ' + error)
}) })
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -4632,17 +5090,17 @@ Obtains the storage usage of an origin in the Web SQL database, in bytes. This A ...@@ -4632,17 +5090,17 @@ Obtains the storage usage of an origin in the Web SQL database, in bytes. This A
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController();
origin: string = "origin"; origin: string = "origin"
build() { build() {
Column() { Column() {
Button('getOriginUsage') Button('getOriginUsage')
.onClick(() => { .onClick(() => {
web_webview.WebStorage.getOriginUsage(this.origin, (error, usage) => { web_webview.WebStorage.getOriginUsage(this.origin, (error, usage) => {
if (error) { if (error) {
console.log('error: ' + error); console.log('error: ' + error)
return; return
} }
console.log('usage: ' + usage); console.log('usage: ' + usage)
}) })
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -4678,17 +5136,17 @@ Obtains the storage usage of an origin in the Web SQL database, in bytes. This A ...@@ -4678,17 +5136,17 @@ Obtains the storage usage of an origin in the Web SQL database, in bytes. This A
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController();
origin: string = "origin"; origin: string = "origin"
build() { build() {
Column() { Column() {
Button('getOriginQuota') Button('getOriginQuota')
.onClick(() => { .onClick(() => {
web_webview.WebStorage.getOriginUsage(this.origin) web_webview.WebStorage.getOriginUsage(this.origin)
.then(usage => { .then(usage => {
console.log('usage: ' + usage); console.log('usage: ' + usage)
}) })
.catch(error => { .catch(error => {
console.log('error: ' + error); console.log('error: ' + error)
}) })
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -4716,27 +5174,27 @@ Searches the web page for content that matches the keyword specified by **'searc ...@@ -4716,27 +5174,27 @@ Searches the web page for content that matches the keyword specified by **'searc
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
@State searchString: string = "xxx"; @State searchString: string = "xxx"
build() { build() {
Column() { Column() {
Button('searchString') Button('searchString')
.onClick(() => { .onClick(() => {
this.controller.searchAllAsync(this.searchString); this.controller.searchAllAsync(this.searchString)
}) })
Button('clearMatches') Button('clearMatches')
.onClick(() => { .onClick(() => {
this.controller.clearMatches(); this.controller.clearMatches()
}) })
Button('searchNext') Button('searchNext')
.onClick(() => { .onClick(() => {
this.controller.searchNext(true); this.controller.searchNext(true)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.onSearchResultReceive(ret => { .onSearchResultReceive(ret => {
console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal + console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal +
"[total]" + ret.numberOfMatches + "[isDone]"+ ret.isDoneCounting); "[total]" + ret.numberOfMatches + "[isDone]"+ ret.isDoneCounting)
}) })
} }
} }
...@@ -4756,13 +5214,13 @@ Clears the matches found through [searchAllAsync](#searchallasync9). ...@@ -4756,13 +5214,13 @@ Clears the matches found through [searchAllAsync](#searchallasync9).
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('clearMatches') Button('clearMatches')
.onClick(() => { .onClick(() => {
this.controller.clearMatches(); this.controller.clearMatches()
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -4790,13 +5248,13 @@ Searches for and highlights the next match. ...@@ -4790,13 +5248,13 @@ Searches for and highlights the next match.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('searchNext') Button('searchNext')
.onClick(() => { .onClick(() => {
this.controller.searchNext(true); this.controller.searchNext(true)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -4825,14 +5283,14 @@ Invoked to notify the caller of the search result on the web page. ...@@ -4825,14 +5283,14 @@ Invoked to notify the caller of the search result on the web page.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.onSearchResultReceive(ret => { .onSearchResultReceive(ret => {
console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal + console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal +
"[total]" + ret.numberOfMatches + "[isDone]"+ ret.isDoneCounting); "[total]" + ret.numberOfMatches + "[isDone]"+ ret.isDoneCounting)
}) })
} }
} }
...@@ -4851,7 +5309,7 @@ Provides usage information about the Web SQL database. ...@@ -4851,7 +5309,7 @@ Provides usage information about the Web SQL database.
| usage | number | Yes | Storage usage of the origin. | | usage | number | Yes | Storage usage of the origin. |
| quota | number | Yes | Storage quota of the origin. | | quota | number | Yes | Storage quota of the origin. |
## MessageLevel enums ## MessageLevel
| Name | Description | | Name | Description |
| ----- | :---- | | ----- | :---- |
...@@ -4863,7 +5321,7 @@ Provides usage information about the Web SQL database. ...@@ -4863,7 +5321,7 @@ Provides usage information about the Web SQL database.
## RenderExitReason ## RenderExitReason
Explains why the rendering process exits. Enumerates the reasons why the rendering process exits.
| Name | Description | | Name | Description |
| -------------------------- | ----------------- | | -------------------------- | ----------------- |
...@@ -4939,17 +5397,17 @@ webAsyncController: WebAsyncController = new WebAsyncController(webController); ...@@ -4939,17 +5397,17 @@ webAsyncController: WebAsyncController = new WebAsyncController(webController);
### storeWebArchive<sup>9+</sup> ### storeWebArchive<sup>9+</sup>
storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback<string>): void storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback\<string>): void
Saves the current web page. This API uses an asynchronous callback to return the result. Stores this web page. This API uses an asynchronous callback to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------------------------- | | -------- | ---------------------------------------- | ---- | ----------------------------------- |
| baseName | string | Yes| Save path. The value cannot be null. | baseName | string | Yes| Save path. The value cannot be null. |
| autoName | boolean | Yes| Whether to automatically generate a file name.<br>The value **false** means not to automatically generate a file name.<br>The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. | autoName | boolean | Yes| Whether to automatically generate a file name.<br>The value **false** means not to automatically generate a file name.<br>The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. |
| callback | AsyncCallback<string> | Yes | Callback used to return the save path if the operation is successful and null otherwise.| | callback | AsyncCallback\<string> | Yes | Callback used to return the save path if the operation is successful and null otherwise.|
**Example** **Example**
...@@ -4959,17 +5417,17 @@ Saves the current web page. This API uses an asynchronous callback to return the ...@@ -4959,17 +5417,17 @@ Saves the current web page. This API uses an asynchronous callback to return the
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
build() { build() {
Column() { Column() {
Button('saveWebArchive') Button('saveWebArchive')
.onClick(() => { .onClick(() => {
let webAsyncController = new web_webview.WebAsyncController(this.controller); let webAsyncController = new web_webview.WebAsyncController(this.controller)
webAsyncController.storeWebArchive("/data/storage/el2/base/", true, (filename) => { webAsyncController.storeWebArchive("/data/storage/el2/base/", true, (filename) => {
if (filename != null) { if (filename != null) {
console.info(`save web archive success: ${filename}`) console.info(`save web archive success: ${filename}`)
} }
}); })
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -4979,22 +5437,22 @@ Saves the current web page. This API uses an asynchronous callback to return the ...@@ -4979,22 +5437,22 @@ Saves the current web page. This API uses an asynchronous callback to return the
### storeWebArchive<sup>9+</sup> ### storeWebArchive<sup>9+</sup>
storeWebArchive(baseName: string, autoName: boolean): Promise<string> storeWebArchive(baseName: string, autoName: boolean): Promise\<string>
Stores the current web page. This API uses an asynchronous callback to return the result. Stores this web page. This API uses a promise to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------------------------- | | -------- | ---------------------------------------- | ---- | ----------------------------------- |
| baseName | string | Yes| Save path. The value cannot be null. | baseName | string | Yes| Save path. The value cannot be null. |
| autoName | boolean | Yes| Whether to automatically generate a file name.<br>The value **false** means not to automatically generate a file name.<br>The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. | autoName | boolean | Yes| Whether to automatically generate a file name.<br>The value **false** means not to automatically generate a file name.<br>The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------------- | ---------------------------------------- | | ---------------- | ------------------------------------------------------------ |
| Promise<string> | Promise used to return the save path if the operation is successful and null otherwise.| | Promise\<string> | Promise used to return the save path if the operation is successful and null otherwise. |
**Example** **Example**
...@@ -5025,7 +5483,7 @@ Stores the current web page. This API uses an asynchronous callback to return th ...@@ -5025,7 +5483,7 @@ Stores the current web page. This API uses an asynchronous callback to return th
## WebMessagePort<sup>9+</sup> ## WebMessagePort<sup>9+</sup>
Defines a **WebMessagePort** instance, which can can be used to send and receive messages. Defines a **WebMessagePort** instance, which can be used to send and receive messages.
### close<sup>9+</sup> ### close<sup>9+</sup>
close(): void close(): void
...@@ -5035,7 +5493,7 @@ Disables this message port. ...@@ -5035,7 +5493,7 @@ Disables this message port.
### postMessageEvent<sup>9+</sup> ### postMessageEvent<sup>9+</sup>
postMessageEvent(message: WebMessageEvent): void postMessageEvent(message: WebMessageEvent): void
Sends messages. Sends messages. For the complete sample code, see [postMessage](#postmessage9).
**Parameters** **Parameters**
...@@ -5050,16 +5508,16 @@ Sends messages. ...@@ -5050,16 +5508,16 @@ Sends messages.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
ports: WebMessagePort[] = null; ports: WebMessagePort[] = null
build() { build() {
Column() { Column() {
Button('postMessageEvent') Button('postMessageEvent')
.onClick(() => { .onClick(() => {
var msg = new WebMessageEvent(); var msg = new WebMessageEvent()
msg.setData("post message from ets to html5"); msg.setData("post message from ets to html5")
this.ports[0].postMessageEvent(msg); this.ports[0].postMessageEvent(msg)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -5070,7 +5528,7 @@ Sends messages. ...@@ -5070,7 +5528,7 @@ Sends messages.
### onMessageEvent<sup>9+</sup> ### onMessageEvent<sup>9+</sup>
onMessageEvent(callback: (result: string) => void): void onMessageEvent(callback: (result: string) => void): void
Registers a callback to receive messages from an HTML5 page. Registers a callback to receive messages from an HTML5 page. For the complete sample code, see [postMessage](#postmessage9).
**Parameters** **Parameters**
...@@ -5085,8 +5543,8 @@ Registers a callback to receive messages from an HTML5 page. ...@@ -5085,8 +5543,8 @@ Registers a callback to receive messages from an HTML5 page.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
ports: WebMessagePort[] = null; ports: WebMessagePort[] = null
build() { build() {
Column() { Column() {
...@@ -5130,9 +5588,9 @@ Obtains the messages stored in this object. ...@@ -5130,9 +5588,9 @@ Obtains the messages stored in this object.
Button('getPorts') Button('getPorts')
.onClick(() => { .onClick(() => {
var msgEvent = new WebMessageEvent(); var msgEvent = new WebMessageEvent();
msgEvent.setData("message event data"); msgEvent.setData("message event data")
var messageData = msgEvent.getData(); var messageData = msgEvent.getData()
console.log("message is:" + messageData); console.log("message is:" + messageData)
}) })
} }
} }
...@@ -5142,7 +5600,7 @@ Obtains the messages stored in this object. ...@@ -5142,7 +5600,7 @@ Obtains the messages stored in this object.
### setData<sup>9+</sup> ### setData<sup>9+</sup>
setData(data: string): void setData(data: string): void
Sets the message in this object. Sets the message in this object. For the complete sample code, see [postMessage](#postmessage9).
**Parameters** **Parameters**
...@@ -5157,16 +5615,16 @@ Sets the message in this object. ...@@ -5157,16 +5615,16 @@ Sets the message in this object.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
ports: WebMessagePort[] = null; ports: WebMessagePort[] = null
build() { build() {
Column() { Column() {
Button('setData') Button('setData')
.onClick(() => { .onClick(() => {
var msg = new WebMessageEvent(); var msg = new WebMessageEvent()
msg.setData("post message from ets to HTML5"); msg.setData("post message from ets to HTML5")
this.ports[0].postMessageEvent(msg); this.ports[0].postMessageEvent(msg)
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -5191,16 +5649,16 @@ Obtains the message port stored in this object. ...@@ -5191,16 +5649,16 @@ Obtains the message port stored in this object.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
ports: WebMessagePort[] = null; ports: WebMessagePort[] = null
build() { build() {
Column() { Column() {
Button('getPorts') Button('getPorts')
.onClick(() => { .onClick(() => {
var sendPortArray = new Array(this.ports[0]); var sendPortArray = new Array(this.ports[0])
var msgEvent = new WebMessageEvent(); var msgEvent = new WebMessageEvent()
msgEvent.setPorts(sendPortArray); msgEvent.setPorts(sendPortArray)
var getPorts = msgEvent.getPorts(); var getPorts = msgEvent.getPorts()
console.log("Ports is:" + getPorts); console.log("Ports is:" + getPorts)
}) })
} }
} }
...@@ -5210,7 +5668,7 @@ Obtains the message port stored in this object. ...@@ -5210,7 +5668,7 @@ Obtains the message port stored in this object.
### setPorts<sup>9+</sup> ### setPorts<sup>9+</sup>
setPorts(ports: Array\<WebMessagePort\>): void setPorts(ports: Array\<WebMessagePort\>): void
Sets the message port in this object. Sets the message port in this object. For the complete sample code, see [postMessage](#postmessage9).
**Parameters** **Parameters**
...@@ -5225,18 +5683,18 @@ Sets the message port in this object. ...@@ -5225,18 +5683,18 @@ Sets the message port in this object.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController()
ports: WebMessagePort[] = null; ports: WebMessagePort[] = null
build() { build() {
Column() { Column() {
Button('setPorts') Button('setPorts')
.onClick(() => { .onClick(() => {
var sendPortArray = new Array(this.ports[1]); var sendPortArray = new Array(this.ports[1])
var msgEvent = new WebMessageEvent(); var msgEvent = new WebMessageEvent()
msgEvent.setData("__init_ports__"); msgEvent.setData("__init_ports__")
msgEvent.setPorts(sendPortArray); msgEvent.setPorts(sendPortArray)
this.controller.postMessage({message: msgEvent, uri: "*"}); this.controller.postMessage({message: msgEvent, uri: "*"})
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
......
...@@ -7,11 +7,6 @@ The **\<XComponent>** can accept and display the EGL/OpenGL ES and media data in ...@@ -7,11 +7,6 @@ The **\<XComponent>** can accept and display the EGL/OpenGL ES and media data in
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
Not supported Not supported
...@@ -25,7 +20,7 @@ XComponent(value: {id: string, type: string, libraryname?: string, controller?: ...@@ -25,7 +20,7 @@ XComponent(value: {id: string, type: string, libraryname?: string, controller?:
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ----- | | --------- | ------ | ---- | ----- |
| id | string | Yes | Unique ID of the component. The value can contain a maximum of 128 characters.| | id | string | Yes | Unique ID of the component. The value can contain a maximum of 128 characters.|
| type | string | Yes | Type of the component. The options are as follows:<br>-**surface**: The content of this component is displayed individually, without being combined with that of other components.<br>-**component**: The content of this component is displayed after having been combined with that of other components.| | type | string | Yes | Type of the component. The options are as follows:<br>- **surface**: The content of this component is displayed individually, without being combined with that of other components.<br>- **component**: The content of this component is displayed after having been combined with that of other components. |
| libraryname | string | No | Name of the dynamic library generated after compilation at the application native layer.| | libraryname | string | No | Name of the dynamic library generated after compilation at the application native layer.|
| controller | [XComponentcontroller](#xcomponentcontroller) | No | Controller bound to the component, which can be used to invoke methods of the component.| | controller | [XComponentcontroller](#xcomponentcontroller) | No | Controller bound to the component, which can be used to invoke methods of the component.|
...@@ -110,7 +105,7 @@ You can preview how this component looks on a real device. The preview is not ye ...@@ -110,7 +105,7 @@ You can preview how this component looks on a real device. The preview is not ye
```ts ```ts
// xxx.ets // xxx.ets
import camera from '@ohos.multimedia.camera'; import camera from '@ohos.multimedia.camera'
@Entry @Entry
@Component @Component
struct PreviewArea { struct PreviewArea {
...@@ -125,9 +120,9 @@ struct PreviewArea { ...@@ -125,9 +120,9 @@ struct PreviewArea {
}) })
.onLoad(() => { .onLoad(() => {
this.xcomponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080}); this.xcomponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080});
this.surfaceId = this.xcomponentController.getXComponentSurfaceId(); this.surfaceId = this.xcomponentController.getXComponentSurfaceId()
camera.createPreviewOutput(this.surfaceId).then((previewOutput) => { camera.createPreviewOutput(this.surfaceId).then((previewOutput) => {
console.log('Promise returned with the PreviewOutput instance'); console.log('Promise returned with the PreviewOutput instance')
}) })
}) })
.width('640px') .width('640px')
......
...@@ -24,9 +24,9 @@ LongPressGesture(value?: { fingers?: number, repeat?: boolean, duration?: number ...@@ -24,9 +24,9 @@ LongPressGesture(value?: { fingers?: number, repeat?: boolean, duration?: number
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onAction(event:(event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Callback invoked when a long press gesture is recognized.| | onAction(event:(event?: [GestureEvent](ts-gesture-settings.md#gestureevent)) =&gt; void) | Invoked when a long press gesture is recognized.|
| onActionEnd(event:(event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Callback invoked when the finger used for a long press gesture is lift.| | onActionEnd(event:(event?: [GestureEvent](ts-gesture-settings.md#gestureevent)) =&gt; void) | Invoked when the finger used for a long press gesture is lift.|
| onActionCancel(event: () =&gt; void) | Callback invoked when a tap cancellation event is received after a long press gesture is recognized.| | onActionCancel(event: () =&gt; void) | Invoked when a tap cancellation event is received after a long press gesture is recognized.|
## Example ## Example
...@@ -39,15 +39,16 @@ struct LongPressGestureExample { ...@@ -39,15 +39,16 @@ struct LongPressGestureExample {
@State count: number = 0 @State count: number = 0
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) { Column() {
Text('LongPress onAction:' + this.count) Text('LongPress onAction:' + this.count).fontSize(28)
} // Touch and hold the text with one finger to trigger the gesture event.
.height(200).width(300).padding(60).border({ width:1 }).margin(30)
.gesture( .gesture(
LongPressGesture({ repeat: true }) LongPressGesture({ repeat: true })
// Repeatedly triggered when the long press gesture exists. // When repeat is set to true, the event callback is triggered continuously when the gesture is detected. The triggering interval is specified by duration (500 ms by default).
.onAction((event: GestureEvent) => { .onAction((event: GestureEvent) => {
if (event.repeat) { this.count++ } if (event.repeat) {
this.count++
}
}) })
// Triggered when the long press gesture ends. // Triggered when the long press gesture ends.
.onActionEnd(() => { .onActionEnd(() => {
...@@ -55,6 +56,12 @@ struct LongPressGestureExample { ...@@ -55,6 +56,12 @@ struct LongPressGestureExample {
}) })
) )
} }
.height(200)
.width(300)
.padding(20)
.border({ width: 3 })
.margin(30)
}
} }
``` ```
......
# PanGesture # PanGesture
**PanGesture** is used to trigger a pan gesture, which requires a minimum 5 vp movement distance of a finger on the screen. **PanGesture** is used to trigger a pan gesture, which requires a minimum 5 vp movement distance of a finger on the screen.
...@@ -17,7 +19,7 @@ PanGesture(value?: { fingers?: number; direction?: PanDirection; distance?: numb ...@@ -17,7 +19,7 @@ PanGesture(value?: { fingers?: number; direction?: PanDirection; distance?: numb
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| fingers | number | No| Minimum number of fingers to trigger a pan gesture. The value ranges from 1 to 10.<br>Default value: **1**| | fingers | number | No| Minimum number of fingers to trigger a pan gesture. The value ranges from 1 to 10.<br>Default value: **1**|
| direction | PanDirection | No| Pan direction. The enumerated value supports the AND (&amp;) and OR (\|) operations.<br>Default value: **PanDirection.All**| | direction | PanDirection | No| Pan direction. The enumerated value supports the AND (&amp;) and OR (\|) operations.<br>Default value: **PanDirection.All**|
| distance | number | No| Minimum pan distance to trigger the gesture, in vp.<br>Default value: **5.0**<br>**NOTE**<br>If a pan gesture and tab swipe occur at the same time, set **distance** to **1** so that the gesture can be more easily recognized.| | distance | number | No| Minimum pan distance to trigger the gesture, in vp.<br>Default value: **5**<br>**NOTE**<br>If a pan gesture and tab swipe occur at the same time, set **distance** to **1** so that the gesture can be more easily recognized.|
## PanDirection enums ## PanDirection enums
...@@ -60,10 +62,10 @@ PanGestureOptions(value?: { fingers?: number; direction?: PanDirection; distance ...@@ -60,10 +62,10 @@ PanGestureOptions(value?: { fingers?: number; direction?: PanDirection; distance
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onActionStart(event: (event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Callback invoked when a pan gesture is recognized.| | onActionStart(event: (event?: [GestureEvent](ts-gesture-settings.md#gestureevent)) =&gt; void) | Invoked when a pan gesture is recognized.|
| onActionUpdate(event: (event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Callback invoked when the pan gesture status is updated.| | onActionUpdate(event: (event?: [GestureEvent](ts-gesture-settings.md#gestureevent)) =&gt; void) | Invoked when the pan gesture status is updated.|
| onActionEnd(event: (event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Callback invoked when the finger used for a pan gesture is lift.| | onActionEnd(event: (event?: [GestureEvent](ts-gesture-settings.md#gestureevent)) =&gt; void) | Invoked when the finger used for a pan gesture is lift.|
| onActionCancel(event: () =&gt; void) | Callback invoked when a tap cancellation event is received after a pan gesture is recognized.| | onActionCancel(event: () =&gt; void) | Invoked when a tap cancellation event is received after a pan gesture is recognized.|
## Example ## Example
...@@ -75,28 +77,55 @@ PanGestureOptions(value?: { fingers?: number; direction?: PanDirection; distance ...@@ -75,28 +77,55 @@ PanGestureOptions(value?: { fingers?: number; direction?: PanDirection; distance
struct PanGestureExample { struct PanGestureExample {
@State offsetX: number = 0 @State offsetX: number = 0
@State offsetY: number = 0 @State offsetY: number = 0
@State positionX: number = 0
@State positionY: number = 0
private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Left | PanDirection.Right })
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) { Column() {
Column() {
Text('PanGesture offset:\nX: ' + this.offsetX + '\n' + 'Y: ' + this.offsetY) Text('PanGesture offset:\nX: ' + this.offsetX + '\n' + 'Y: ' + this.offsetY)
} }
.height(100).width(200).padding(20).border({ width: 1 }).margin(80) .height(200)
.translate({ x: this.offsetX, y: this.offsetY, z: 5 }) .width(300)
.padding(20)
.border({ width: 3 })
.margin(50)
.translate({ x: this.offsetX, y: this.offsetY, z: 0 })
// Pan left or right to trigger the gesture event.
.gesture( .gesture(
PanGesture({}) PanGesture(this.panOption)
.onActionStart((event: GestureEvent) => { .onActionStart((event: GestureEvent) => {
console.info('Pan start') console.info('Pan start')
}) })
.onActionUpdate((event: GestureEvent) => { .onActionUpdate((event: GestureEvent) => {
this.offsetX = event.offsetX this.offsetX = this.positionX + event.offsetX
this.offsetY = event.offsetY this.offsetY = this.positionY + event.offsetY
}) })
.onActionEnd(() => { .onActionEnd(() => {
this.positionX = this.offsetX
this.positionY = this.offsetY
console.info('Pan end') console.info('Pan end')
}) })
) )
Button ('Set PanGesture Trigger Condition')
.onClick(() => {
// Set the pan gesture to be triggered by two fingers moving in any direction.
this.panOption.setDirection(PanDirection.All)
this.panOption.setFingers(2)
})
}
} }
} }
``` ```
![en-us_image_0000001256978371](figures/en-us_image_0000001256978371.gif) **Diagrams**
Pannig to the left:
![en-us_image_0000001174264374](figures/en-us_image_0000001174264374.png)
Click Set PanGesture Trigger Condition to two fingers moving toward the lower left corner.
![en-us_image1_0000001174264374](figures/en-us_image1_0000001174264374.png)
...@@ -16,16 +16,16 @@ PinchGesture(value?: { fingers?: number, distance?: number }) ...@@ -16,16 +16,16 @@ PinchGesture(value?: { fingers?: number, distance?: number })
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| fingers | number | No| Minimum number of fingers to trigger a pinch. The value ranges from 2 to 5.<br>Default value: **2**| | fingers | number | No| Minimum number of fingers to trigger a pinch. The value ranges from 2 to 5.<br>Default value: **2**|
| distance | number | No| Minimum recognition distance, in vp.<br>Default value: **3.0**| | distance | number | No| Minimum recognition distance, in vp.<br>Default value: **3**|
## Events ## Events
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onActionStart(event:(event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Triggered when a pinch gesture is recognized.| | onActionStart(event:(event?: [GestureEvent](ts-gesture-settings.md#gestureevent)) =&gt; void) | Triggered when a pinch gesture is recognized.|
| onActionUpdate(event:(event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Triggered when the user moves the finger in a pinch gesture on the screen.| | onActionUpdate(event:(event?: [GestureEvent](ts-gesture-settings.md#gestureevent)) =&gt; void) | Triggered when the user moves the finger in a pinch gesture on the screen.|
| onActionEnd(event:(event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Triggered when the finger used for a pinch gesture is lift.| | onActionEnd(event:(event?: [GestureEvent](ts-gesture-settings.md#gestureevent)) =&gt; void) | Triggered when the finger used for a pinch gesture is lift.|
| onActionCancel(event: () =&gt; void) | Triggered when a tap cancellation event is received after a pinch gesture is recognized.| | onActionCancel(event: () =&gt; void) | Triggered when a tap cancellation event is received after a pinch gesture is recognized.|
...@@ -37,27 +37,41 @@ PinchGesture(value?: { fingers?: number, distance?: number }) ...@@ -37,27 +37,41 @@ PinchGesture(value?: { fingers?: number, distance?: number })
@Component @Component
struct PinchGestureExample { struct PinchGestureExample {
@State scaleValue: number = 1 @State scaleValue: number = 1
@State pinchValue: number = 1
@State pinchX: number = 0
@State pinchY: number = 0
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) { Column() {
Text('PinchGesture scale:' + this.scale) Column() {
Text('PinchGesture scale:\n' + this.scaleValue)
Text('PinchGesture center:\n(' + this.pinchX + ',' + this.pinchY + ')')
} }
.height(100).width(200).padding(20).border({ width: 1 }).margin(80) .height(200)
.scale({ x: this.scaleValue, y: this.scaleValue, z: this.scaleValue }) .width(300)
.padding(20)
.border({ width: 3 })
.margin({ top: 100 })
.scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
// The gesture event is triggered by pinching three fingers together.
.gesture( .gesture(
PinchGesture() PinchGesture({ fingers: 3 })
.onActionStart((event: GestureEvent) => { .onActionStart((event: GestureEvent) => {
console.info('Pinch start') console.info('Pinch start')
}) })
.onActionUpdate((event: GestureEvent) => { .onActionUpdate((event: GestureEvent) => {
this.scaleValue = event.scale this.scaleValue = this.pinchValue * event.scale
this.pinchX = event.pinchCenterX
this.pinchY = event.pinchCenterY
}) })
.onActionEnd(() => { .onActionEnd(() => {
this.pinchValue = this.scaleValue
console.info('Pinch end') console.info('Pinch end')
}) })
) )
}.width('100%')
} }
} }
``` ```
![en-us_image_0000001257058419](figures/en-us_image_0000001257058419.gif) ![en-us_image_0000001174582848](figures/en-us_image_0000001174582848.png)
...@@ -16,16 +16,16 @@ RotationGesture(value?: { fingers?: number, angle?: number }) ...@@ -16,16 +16,16 @@ RotationGesture(value?: { fingers?: number, angle?: number })
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| fingers | number | No| Minimum number of fingers to trigger a rotation. The value ranges from 2 to 5.<br>Default value: **2**| | fingers | number | No| Minimum number of fingers to trigger a rotation. The value ranges from 2 to 5.<br>Default value: **2**|
| angle | number | No| Minimum degree that can trigger the rotation gesture.<br>Default value: **1.0**| | angle | number | No| Minimum degree that can trigger the rotation gesture.<br>Default value: **1**|
## Events ## Events
| Parameter| Description| | Parameter| Description|
| -------- | -------- | | -------- | -------- |
| onActionStart(event:(event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Triggered when a rotation gesture is recognized.| | onActionStart(event:(event?: [GestureEvent](ts-gesture-settings.md#gestureevent)) =&gt; void) | Triggered when a rotation gesture is recognized.|
| onActionUpdate(event:(event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Triggered when the user moves the finger in a rotation gesture on the screen.| | onActionUpdate(event:(event?: [GestureEvent](ts-gesture-settings.md#gestureevent)) =&gt; void) | Triggered when the user moves the finger in a rotation gesture on the screen.|
| onActionEnd(event:(event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Triggered when the finger used for the rotation gesture is lift.| | onActionEnd(event:(event?: [GestureEvent](ts-gesture-settings.md#gestureevent)) =&gt; void) | Triggered when the finger used for the rotation gesture is lift.|
| onActionCancel(event: () =&gt; void) | Triggered when a tap cancellation event is received after the rotation gesture is recognized.| | onActionCancel(event: () =&gt; void) | Triggered when a tap cancellation event is received after the rotation gesture is recognized.|
...@@ -37,27 +37,36 @@ RotationGesture(value?: { fingers?: number, angle?: number }) ...@@ -37,27 +37,36 @@ RotationGesture(value?: { fingers?: number, angle?: number })
@Component @Component
struct RotationGestureExample { struct RotationGestureExample {
@State angle: number = 0 @State angle: number = 0
@State rotateValue: number = 0
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) { Column() {
Column() {
Text('RotationGesture angle:' + this.angle) Text('RotationGesture angle:' + this.angle)
} }
.height(100).width(200).padding(20).border({ width:1 }) .height(200)
.margin(80).rotate({ x:1, y:2, z:3, angle: this.angle }) .width(300)
.padding(20)
.border({ width: 3 })
.margin(80)
.rotate({ angle: this.angle })
// The gesture event is triggered by rotating with two fingers.
.gesture( .gesture(
RotationGesture() RotationGesture()
.onActionStart((event: GestureEvent) => { .onActionStart((event: GestureEvent) => {
console.log('Rotation start') console.info('Rotation start')
}) })
.onActionUpdate((event: GestureEvent) => { .onActionUpdate((event: GestureEvent) => {
this.angle = event.angle this.angle = this.rotateValue + event.angle
}) })
.onActionEnd(() => { .onActionEnd(() => {
console.log('Rotation end') this.rotateValue = this.angle
console.info('Rotation end')
}) })
) )
}.width('100%')
} }
} }
``` ```
![en-us_image_0000001256858403](figures/en-us_image_0000001256858403.gif) ![en-us_image_0000001174264372](figures/en-us_image_0000001174264372.png)
...@@ -42,8 +42,8 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num ...@@ -42,8 +42,8 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num
@Entry @Entry
@Component @Component
struct SwipeGestureExample { struct SwipeGestureExample {
@State rotateAngle: number = 0; @State rotateAngle: number = 0
@State speed: number = 1; @State speed: number = 1
build() { build() {
Column() { Column() {
...@@ -60,8 +60,8 @@ struct SwipeGestureExample { ...@@ -60,8 +60,8 @@ struct SwipeGestureExample {
.gesture( .gesture(
SwipeGesture({ direction: SwipeDirection.Vertical }) SwipeGesture({ direction: SwipeDirection.Vertical })
.onAction((event: GestureEvent) => { .onAction((event: GestureEvent) => {
this.speed = event.speed; this.speed = event.speed
this.rotateAngle = event.angle; this.rotateAngle = event.angle
}) })
) )
}.width('100%') }.width('100%')
......
...@@ -16,14 +16,14 @@ TapGesture(value?: { count?: number, fingers?: number }) ...@@ -16,14 +16,14 @@ TapGesture(value?: { count?: number, fingers?: number })
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| count | number | No| Number of consecutive taps. If this parameter is set to a value less than **1**, the default value will be used.<br>Default value: **1**<br>> **NOTE**<br>> If multi-tap is configured, the timeout interval between a lift and the next tap is 300 ms.| | count | number | No| Number of consecutive taps. If this parameter is set to a value less than **1**, the default value will be used.<br>Default value: **1**<br>> **NOTE**<br>> If multi-tap is configured, the timeout interval between a lift and the next tap is 300 ms.|
| fingers | number | No| Minimum number of fingers to trigger a tap. The value ranges from 1 to 10.<br>Default value: **1**<br>> **NOTE**<br>> 1. When multi-finger is configured, the gesture will fail to be recognized if the number of fingers used for tapping is less than the configured number within 300 ms after the first finger is tapped.<br>> 2. The gesture will fail to be recognized if the number of fingers used for tapping exceeds the configured number.| | fingers | number | No| Number of fingers required to trigger a tap. The value ranges from 1 to 10.<br>Default value: **1**<br>> **NOTE**<br>> 1. When multi-finger is configured, the gesture will fail to be recognized if the number of fingers used for tapping is less than the configured number within 300 ms of tapping by the first finger.<br>> 2. The gesture will fail to be recognized if the number of fingers used for tapping exceeds the configured number.|
## Events ## Events
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onAction(event: (event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Callback invoked when a tap gesture is recognized.| | onAction(event: (event?: [GestureEvent](ts-gesture-settings.md#gestureevent)) =&gt; void) | Callback invoked when a tap gesture is recognized.|
## Example ## Example
...@@ -36,17 +36,22 @@ struct TapGestureExample { ...@@ -36,17 +36,22 @@ struct TapGestureExample {
@State value: string = '' @State value: string = ''
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) { Column() {
Text('Click twice') // The gesture event is triggered by double-tapping.
Text(this.value) Text('Click twice').fontSize(28)
}
.height(200).width(300).padding(60).border({ width: 1 }).margin(30)
.gesture( .gesture(
TapGesture({ count: 2 }) TapGesture({ count: 2 })
.onAction(() => { .onAction((event: GestureEvent) => {
this.value = 'TapGesture onAction' this.value = JSON.stringify(event.fingerList[0])
}) })
) )
Text(this.value)
}
.height(200)
.width(300)
.padding(20)
.border({ width: 3 })
.margin(30)
} }
} }
``` ```
......
...@@ -29,13 +29,13 @@ Configures the settings of a **CanvasRenderingContext2D** object, including whet ...@@ -29,13 +29,13 @@ Configures the settings of a **CanvasRenderingContext2D** object, including whet
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------- | ---- | ----------------------------- | | --------- | ------- | ---- | ----------------------------- |
| antialias | boolean | No | Whether antialiasing is enabled.<br>Default value: **false**| | antialias | boolean | No | Whether to enable antialiasing.<br>Default value: **false** |
## Attributes ## Attributes
| Name | Type | Description | | Name | Type | Description |
| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | | ----------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Style to fill an area.<br>- When the type is string, this attribute indicates the color of the fill area.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.| | [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Style to fill an area.<br>- When the type is string, this attribute indicates the color of the fill area.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.|
| [lineWidth](#linewidth) | number | Line width. | | [lineWidth](#linewidth) | number | Line width. |
| [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Stroke style.<br>- When the type is string, this attribute indicates the stroke color.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.| | [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Stroke style.<br>- When the type is string, this attribute indicates the stroke color.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.|
...@@ -66,8 +66,8 @@ Configures the settings of a **CanvasRenderingContext2D** object, including whet ...@@ -66,8 +66,8 @@ Configures the settings of a **CanvasRenderingContext2D** object, including whet
@Entry @Entry
@Component @Component
struct FillStyleExample { struct FillStyleExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -96,8 +96,8 @@ struct FillStyleExample { ...@@ -96,8 +96,8 @@ struct FillStyleExample {
@Entry @Entry
@Component @Component
struct LineWidthExample { struct LineWidthExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -126,8 +126,8 @@ struct LineWidthExample { ...@@ -126,8 +126,8 @@ struct LineWidthExample {
@Entry @Entry
@Component @Component
struct StrokeStyleExample { struct StrokeStyleExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -158,8 +158,8 @@ struct StrokeStyleExample { ...@@ -158,8 +158,8 @@ struct StrokeStyleExample {
@Entry @Entry
@Component @Component
struct LineCapExample { struct LineCapExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -192,8 +192,8 @@ struct LineCapExample { ...@@ -192,8 +192,8 @@ struct LineCapExample {
@Entry @Entry
@Component @Component
struct LineJoinExample { struct LineJoinExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -227,8 +227,8 @@ struct LineJoinExample { ...@@ -227,8 +227,8 @@ struct LineJoinExample {
@Entry @Entry
@Component @Component
struct MiterLimit { struct MiterLimit {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -262,8 +262,8 @@ struct MiterLimit { ...@@ -262,8 +262,8 @@ struct MiterLimit {
@Entry @Entry
@Component @Component
struct Fonts { struct Fonts {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -292,8 +292,8 @@ struct Fonts { ...@@ -292,8 +292,8 @@ struct Fonts {
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -337,8 +337,8 @@ struct CanvasExample { ...@@ -337,8 +337,8 @@ struct CanvasExample {
@Entry @Entry
@Component @Component
struct TextBaseline { struct TextBaseline {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -382,8 +382,8 @@ struct TextBaseline { ...@@ -382,8 +382,8 @@ struct TextBaseline {
@Entry @Entry
@Component @Component
struct GlobalAlpha { struct GlobalAlpha {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -415,8 +415,8 @@ struct GlobalAlpha { ...@@ -415,8 +415,8 @@ struct GlobalAlpha {
@Entry @Entry
@Component @Component
struct LineDashOffset { struct LineDashOffset {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -427,8 +427,8 @@ struct LineDashOffset { ...@@ -427,8 +427,8 @@ struct LineDashOffset {
.onReady(() =>{ .onReady(() =>{
this.context.arc(100, 75, 50, 0, 6.28) this.context.arc(100, 75, 50, 0, 6.28)
this.context.setLineDash([10,20]) this.context.setLineDash([10,20])
this.context.lineDashOffset = 10.0; this.context.lineDashOffset = 10.0
this.context.stroke(); this.context.stroke()
}) })
} }
.width('100%') .width('100%')
...@@ -461,8 +461,8 @@ struct LineDashOffset { ...@@ -461,8 +461,8 @@ struct LineDashOffset {
@Entry @Entry
@Component @Component
struct GlobalCompositeOperation { struct GlobalCompositeOperation {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -499,8 +499,8 @@ struct GlobalCompositeOperation { ...@@ -499,8 +499,8 @@ struct GlobalCompositeOperation {
@Entry @Entry
@Component @Component
struct ShadowBlur { struct ShadowBlur {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -531,8 +531,8 @@ struct ShadowBlur { ...@@ -531,8 +531,8 @@ struct ShadowBlur {
@Entry @Entry
@Component @Component
struct ShadowColor { struct ShadowColor {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -563,8 +563,8 @@ struct ShadowColor { ...@@ -563,8 +563,8 @@ struct ShadowColor {
@Entry @Entry
@Component @Component
struct ShadowOffsetX { struct ShadowOffsetX {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -596,8 +596,8 @@ struct ShadowOffsetX { ...@@ -596,8 +596,8 @@ struct ShadowOffsetX {
@Entry @Entry
@Component @Component
struct ShadowOffsetY { struct ShadowOffsetY {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -628,9 +628,9 @@ struct ShadowOffsetY { ...@@ -628,9 +628,9 @@ struct ShadowOffsetY {
@Entry @Entry
@Component @Component
struct ImageSmoothingEnabled { struct ImageSmoothingEnabled {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg"); private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg")
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -677,8 +677,8 @@ Fills a rectangle on the canvas. ...@@ -677,8 +677,8 @@ Fills a rectangle on the canvas.
@Entry @Entry
@Component @Component
struct FillRect { struct FillRect {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -721,8 +721,8 @@ Draws an outlined rectangle on the canvas. ...@@ -721,8 +721,8 @@ Draws an outlined rectangle on the canvas.
@Entry @Entry
@Component @Component
struct StrokeRect { struct StrokeRect {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -765,8 +765,8 @@ Clears the content in a rectangle on the canvas. ...@@ -765,8 +765,8 @@ Clears the content in a rectangle on the canvas.
@Entry @Entry
@Component @Component
struct ClearRect { struct ClearRect {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -797,9 +797,9 @@ Draws filled text on the canvas. ...@@ -797,9 +797,9 @@ Draws filled text on the canvas.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory| Default Value| Description |
| -------- | ------ | ---- | ---- | --------------- | | -------- | ------ | ---- | ------ | ----------------------------- |
| text | string | Yes | "" | Text to draw. | | text | string | Yes | '' | Text to draw. |
| x | number | Yes | 0 | X-coordinate of the lower left corner of the text.| | x | number | Yes | 0 | X-coordinate of the lower left corner of the text.|
| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.| | y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.|
| maxWidth | number | No | - | Maximum width allowed for the text. | | maxWidth | number | No | - | Maximum width allowed for the text. |
...@@ -811,8 +811,8 @@ Draws filled text on the canvas. ...@@ -811,8 +811,8 @@ Draws filled text on the canvas.
@Entry @Entry
@Component @Component
struct FillText { struct FillText {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -842,9 +842,9 @@ Draws a text stroke on the canvas. ...@@ -842,9 +842,9 @@ Draws a text stroke on the canvas.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory| Default Value| Description |
| -------- | ------ | ---- | ---- | --------------- | | -------- | ------ | ---- | ------ | ----------------------------- |
| text | string | Yes | "" | Text to draw. | | text | string | Yes | '' | Text to draw. |
| x | number | Yes | 0 | X-coordinate of the lower left corner of the text.| | x | number | Yes | 0 | X-coordinate of the lower left corner of the text.|
| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.| | y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.|
| maxWidth | number | No | - | Maximum width of the text to be drawn. | | maxWidth | number | No | - | Maximum width of the text to be drawn. |
...@@ -856,8 +856,8 @@ Draws a text stroke on the canvas. ...@@ -856,8 +856,8 @@ Draws a text stroke on the canvas.
@Entry @Entry
@Component @Component
struct StrokeText { struct StrokeText {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -887,14 +887,14 @@ Measures the specified text to obtain its width. This API returns a **TextMetric ...@@ -887,14 +887,14 @@ Measures the specified text to obtain its width. This API returns a **TextMetric
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name| Type | Mandatory| Default Value| Description |
| ---- | ------ | ---- | ---- | ---------- | | ---- | ------ | ---- | ------ | -------------------- |
| text | string | Yes | "" | Text to be measured.| | text | string | Yes | '' | Text to be measured.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ----------- | ------- | | ----------- | ---------------- |
| TextMetrics | **TextMetrics** object.| | TextMetrics | **TextMetrics** object.|
**TextMetrics** **TextMetrics**
...@@ -925,8 +925,8 @@ Measures the specified text to obtain its width. This API returns a **TextMetric ...@@ -925,8 +925,8 @@ Measures the specified text to obtain its width. This API returns a **TextMetric
@Entry @Entry
@Component @Component
struct MeasureText { struct MeasureText {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -968,8 +968,8 @@ Strokes a path. ...@@ -968,8 +968,8 @@ Strokes a path.
@Entry @Entry
@Component @Component
struct Stroke { struct Stroke {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1008,8 +1008,8 @@ Creates a drawing path. ...@@ -1008,8 +1008,8 @@ Creates a drawing path.
@Entry @Entry
@Component @Component
struct BeginPath { struct BeginPath {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1055,8 +1055,8 @@ Moves a drawing path to a target position on the canvas. ...@@ -1055,8 +1055,8 @@ Moves a drawing path to a target position on the canvas.
@Entry @Entry
@Component @Component
struct MoveTo { struct MoveTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1100,8 +1100,8 @@ Connects the current point to a target position using a straight line. ...@@ -1100,8 +1100,8 @@ Connects the current point to a target position using a straight line.
@Entry @Entry
@Component @Component
struct LineTo { struct LineTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1138,8 +1138,8 @@ Draws a closed path. ...@@ -1138,8 +1138,8 @@ Draws a closed path.
@Entry @Entry
@Component @Component
struct ClosePath { struct ClosePath {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1173,10 +1173,10 @@ Creates a pattern for image filling based on a specified source image and repeti ...@@ -1173,10 +1173,10 @@ Creates a pattern for image filling based on a specified source image and repeti
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory| Description |
| ---------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- | | ---------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ |
| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | Yes | null | Source image. For details, see **ImageBitmap**. | | image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | Yes | Source image. For details, see **ImageBitmap**. |
| repetition | string | Yes | "" | Repetition mode. The value can be **"repeat"**, **"repeat-x"**, **"repeat-y"**, or **"no-repeat"**.| | repetition | string | Yes | Repetition mode. The value can be **'repeat'**, **'repeat-x'**, **'repeat-y'**, or **'no-repeat'**.<br>Default value: **''**|
**Return value** **Return value**
...@@ -1191,9 +1191,9 @@ Creates a pattern for image filling based on a specified source image and repeti ...@@ -1191,9 +1191,9 @@ Creates a pattern for image filling based on a specified source image and repeti
@Entry @Entry
@Component @Component
struct CreatePattern { struct CreatePattern {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg"); private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg")
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1240,8 +1240,8 @@ Draws a cubic bezier curve on the canvas. ...@@ -1240,8 +1240,8 @@ Draws a cubic bezier curve on the canvas.
@Entry @Entry
@Component @Component
struct BezierCurveTo { struct BezierCurveTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1287,8 +1287,8 @@ Draws a quadratic curve on the canvas. ...@@ -1287,8 +1287,8 @@ Draws a quadratic curve on the canvas.
@Entry @Entry
@Component @Component
struct QuadraticCurveTo { struct QuadraticCurveTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1297,10 +1297,10 @@ Draws a quadratic curve on the canvas. ...@@ -1297,10 +1297,10 @@ Draws a quadratic curve on the canvas.
.height('100%') .height('100%')
.backgroundColor('#ffff00') .backgroundColor('#ffff00')
.onReady(() =>{ .onReady(() =>{
this.context.beginPath(); this.context.beginPath()
this.context.moveTo(20, 20); this.context.moveTo(20, 20)
this.context.quadraticCurveTo(100, 100, 200, 20); this.context.quadraticCurveTo(100, 100, 200, 20)
this.context.stroke(); this.context.stroke()
}) })
} }
.width('100%') .width('100%')
...@@ -1336,8 +1336,8 @@ Draws an arc on the canvas. ...@@ -1336,8 +1336,8 @@ Draws an arc on the canvas.
@Entry @Entry
@Component @Component
struct Arc { struct Arc {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1383,8 +1383,8 @@ Draws an arc based on the radius and points on the arc. ...@@ -1383,8 +1383,8 @@ Draws an arc based on the radius and points on the arc.
@Entry @Entry
@Component @Component
struct ArcTo { struct ArcTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1393,9 +1393,9 @@ Draws an arc based on the radius and points on the arc. ...@@ -1393,9 +1393,9 @@ Draws an arc based on the radius and points on the arc.
.height('100%') .height('100%')
.backgroundColor('#ffff00') .backgroundColor('#ffff00')
.onReady(() =>{ .onReady(() =>{
this.context.moveTo(100, 20); this.context.moveTo(100, 20)
this.context.arcTo(150, 20, 150, 70, 50); this.context.arcTo(150, 20, 150, 70, 50)
this.context.stroke(); this.context.stroke()
}) })
} }
.width('100%') .width('100%')
...@@ -1424,7 +1424,7 @@ Draws an ellipse in the specified rectangular region on the canvas. ...@@ -1424,7 +1424,7 @@ Draws an ellipse in the specified rectangular region on the canvas.
| rotation | number | Yes | 0 | Rotation angle of the ellipse. The unit is radian. | | rotation | number | Yes | 0 | Rotation angle of the ellipse. The unit is radian. |
| startAngle | number | Yes | 0 | Angle of the start point for drawing the ellipse. The unit is radian.| | startAngle | number | Yes | 0 | Angle of the start point for drawing the ellipse. The unit is radian.|
| endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse. The unit is radian.| | endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse. The unit is radian.|
| counterclockwise | boolean | No | false | Whether to draw the ellipse in the counterclockwise direction. | | counterclockwise | boolean | No | false | Whether to draw the ellipse in the counterclockwise direction.<br>**true**: Draw the arc counterclockwise.<br>**false**: Draw the arc clockwise. |
**Example** **Example**
...@@ -1433,8 +1433,8 @@ Draws an ellipse in the specified rectangular region on the canvas. ...@@ -1433,8 +1433,8 @@ Draws an ellipse in the specified rectangular region on the canvas.
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1479,8 +1479,8 @@ Creates a rectangle on the canvas. ...@@ -1479,8 +1479,8 @@ Creates a rectangle on the canvas.
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1522,8 +1522,8 @@ Fills the area inside a closed path on the canvas. ...@@ -1522,8 +1522,8 @@ Fills the area inside a closed path on the canvas.
@Entry @Entry
@Component @Component
struct Fill { struct Fill {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1574,17 +1574,17 @@ struct Fill { ...@@ -1574,17 +1574,17 @@ struct Fill {
.height('100%') .height('100%')
.backgroundColor('#ffff00') .backgroundColor('#ffff00')
.onReady(() =>{ .onReady(() =>{
let region = new Path2D(); let region = new Path2D()
region.moveTo(30, 90); region.moveTo(30, 90)
region.lineTo(110, 20); region.lineTo(110, 20)
region.lineTo(240, 130); region.lineTo(240, 130)
region.lineTo(60, 130); region.lineTo(60, 130)
region.lineTo(190, 20); region.lineTo(190, 20)
region.lineTo(270, 90); region.lineTo(270, 90)
region.closePath(); region.closePath()
// Fill path // Fill path
this.context.fillStyle = 'green'; this.context.fillStyle = 'green'
this.context.fill(region, "evenodd"); this.context.fill(region, "evenodd")
}) })
} }
.width('100%') .width('100%')
...@@ -1615,8 +1615,8 @@ Sets the current path to a clipping area. ...@@ -1615,8 +1615,8 @@ Sets the current path to a clipping area.
@Entry @Entry
@Component @Component
struct Clip { struct Clip {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1669,9 +1669,9 @@ struct Clip { ...@@ -1669,9 +1669,9 @@ struct Clip {
.height('100%') .height('100%')
.backgroundColor('#ffff00') .backgroundColor('#ffff00')
.onReady(() =>{ .onReady(() =>{
let region = new Path2D(); let region = new Path2D()
region.rect(80,10,20,130); region.rect(80,10,20,130)
region.rect(40,50,100,50); region.rect(40,50,100,50)
this.context.clip(region,"evenodd") this.context.clip(region,"evenodd")
this.context.fillStyle = "rgb(255,0,0)" this.context.fillStyle = "rgb(255,0,0)"
this.context.fillRect(0, 0, this.context.width, this.context.height) this.context.fillRect(0, 0, this.context.width, this.context.height)
...@@ -1739,8 +1739,8 @@ Rotates a canvas clockwise around its coordinate axes. ...@@ -1739,8 +1739,8 @@ Rotates a canvas clockwise around its coordinate axes.
@Entry @Entry
@Component @Component
struct Rotate { struct Rotate {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1782,8 +1782,8 @@ Scales the canvas based on the given scale factors. ...@@ -1782,8 +1782,8 @@ Scales the canvas based on the given scale factors.
@Entry @Entry
@Component @Component
struct Scale { struct Scale {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1839,8 +1839,8 @@ Defines a transformation matrix. To transform a graph, you only need to set para ...@@ -1839,8 +1839,8 @@ Defines a transformation matrix. To transform a graph, you only need to set para
@Entry @Entry
@Component @Component
struct Transform { struct Transform {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1892,8 +1892,8 @@ Resets the existing transformation matrix and creates a new transformation matri ...@@ -1892,8 +1892,8 @@ Resets the existing transformation matrix and creates a new transformation matri
@Entry @Entry
@Component @Component
struct SetTransform { struct SetTransform {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1943,8 +1943,8 @@ Moves the origin of the coordinate system. ...@@ -1943,8 +1943,8 @@ Moves the origin of the coordinate system.
@Entry @Entry
@Component @Component
struct Translate { struct Translate {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1999,9 +1999,9 @@ Draws an image on the canvas. ...@@ -1999,9 +1999,9 @@ Draws an image on the canvas.
@Entry @Entry
@Component @Component
struct ImageExample { struct ImageExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private img:ImageBitmap = new ImageBitmap("common/images/example.jpg"); private img:ImageBitmap = new ImageBitmap("common/images/example.jpg")
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -2010,7 +2010,7 @@ Draws an image on the canvas. ...@@ -2010,7 +2010,7 @@ Draws an image on the canvas.
.height('100%') .height('100%')
.backgroundColor('#ffff00') .backgroundColor('#ffff00')
.onReady(() =>{ .onReady(() =>{
this.context.drawImage( this.img,0,0,500,500,0,0,400,200); this.context.drawImage( this.img,0,0,500,500,0,0,400,200)
}) })
} }
.width('100%') .width('100%')
...@@ -2103,8 +2103,8 @@ Obtains the **[ImageData](ts-components-canvas-imagedata.md)** object created wi ...@@ -2103,8 +2103,8 @@ Obtains the **[ImageData](ts-components-canvas-imagedata.md)** object created wi
@Entry @Entry
@Component @Component
struct GetImageData { struct GetImageData {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private img:ImageBitmap = new ImageBitmap("/common/images/1234.png") private img:ImageBitmap = new ImageBitmap("/common/images/1234.png")
build() { build() {
...@@ -2114,9 +2114,9 @@ struct GetImageData { ...@@ -2114,9 +2114,9 @@ struct GetImageData {
.height('100%') .height('100%')
.backgroundColor('#ffff00') .backgroundColor('#ffff00')
.onReady(() =>{ .onReady(() =>{
this.context.drawImage(this.img,0,0,130,130); this.context.drawImage(this.img,0,0,130,130)
var imagedata = this.context.getImageData(50,50,130,130); var imagedata = this.context.getImageData(50,50,130,130)
this.context.putImageData(imagedata,150,150); this.context.putImageData(imagedata,150,150)
}) })
} }
.width('100%') .width('100%')
...@@ -2155,8 +2155,8 @@ Puts an **[ImageData](ts-components-canvas-imagedata.md)** object onto a rectang ...@@ -2155,8 +2155,8 @@ Puts an **[ImageData](ts-components-canvas-imagedata.md)** object onto a rectang
@Entry @Entry
@Component @Component
struct PutImageData { struct PutImageData {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -2269,7 +2269,7 @@ struct CanvasGetLineDash { ...@@ -2269,7 +2269,7 @@ struct CanvasGetLineDash {
.onReady(() => { .onReady(() => {
this.context.arc(100, 75, 50, 0, 6.28) this.context.arc(100, 75, 50, 0, 6.28)
this.context.setLineDash([10,20]) this.context.setLineDash([10,20])
this.context.stroke(); this.context.stroke()
let res = this.context.getLineDash() let res = this.context.getLineDash()
}) })
} }
...@@ -2383,7 +2383,7 @@ struct ToDataURL { ...@@ -2383,7 +2383,7 @@ struct ToDataURL {
.height('100%') .height('100%')
.backgroundColor('#ffff00') .backgroundColor('#ffff00')
.onReady(() =>{ .onReady(() =>{
var dataURL = this.context.toDataURL(); var dataURL = this.context.toDataURL()
}) })
} }
.width('100%') .width('100%')
...@@ -2406,8 +2406,8 @@ Restores the saved drawing context. ...@@ -2406,8 +2406,8 @@ Restores the saved drawing context.
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -2416,11 +2416,11 @@ Restores the saved drawing context. ...@@ -2416,11 +2416,11 @@ Restores the saved drawing context.
.height('100%') .height('100%')
.backgroundColor('#ffff00') .backgroundColor('#ffff00')
.onReady(() =>{ .onReady(() =>{
this.context.save(); // save the default state this.context.save() // save the default state
this.context.fillStyle = "green"; this.context.fillStyle = "green"
this.context.fillRect(20, 20, 100, 100); this.context.fillRect(20, 20, 100, 100)
this.context.restore(); // restore to the default state this.context.restore() // restore to the default state
this.context.fillRect(150, 75, 100, 100); this.context.fillRect(150, 75, 100, 100)
}) })
} }
.width('100%') .width('100%')
...@@ -2444,8 +2444,8 @@ Saves all states of the canvas in the stack. This API is usually called when the ...@@ -2444,8 +2444,8 @@ Saves all states of the canvas in the stack. This API is usually called when the
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -2454,11 +2454,11 @@ Saves all states of the canvas in the stack. This API is usually called when the ...@@ -2454,11 +2454,11 @@ Saves all states of the canvas in the stack. This API is usually called when the
.height('100%') .height('100%')
.backgroundColor('#ffff00') .backgroundColor('#ffff00')
.onReady(() =>{ .onReady(() =>{
this.context.save(); // save the default state this.context.save() // save the default state
this.context.fillStyle = "green"; this.context.fillStyle = "green"
this.context.fillRect(20, 20, 100, 100); this.context.fillRect(20, 20, 100, 100)
this.context.restore(); // restore to the default state this.context.restore() // restore to the default state
this.context.fillRect(150, 75, 100, 100); this.context.fillRect(150, 75, 100, 100)
}) })
} }
.width('100%') .width('100%')
...@@ -2491,8 +2491,8 @@ Creates a linear gradient. ...@@ -2491,8 +2491,8 @@ Creates a linear gradient.
@Entry @Entry
@Component @Component
struct CreateLinearGradient { struct CreateLinearGradient {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -2542,8 +2542,8 @@ Creates a linear gradient. ...@@ -2542,8 +2542,8 @@ Creates a linear gradient.
@Entry @Entry
@Component @Component
struct CreateRadialGradient { struct CreateRadialGradient {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......
...@@ -22,9 +22,9 @@ An **ImageBitmap** object stores pixel data rendered on a canvas. ...@@ -22,9 +22,9 @@ An **ImageBitmap** object stores pixel data rendered on a canvas.
@Entry @Entry
@Component @Component
struct ImageExample { struct ImageExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private img:ImageBitmap = new ImageBitmap("common/images/example.jpg"); private img:ImageBitmap = new ImageBitmap("common/images/example.jpg")
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -33,7 +33,7 @@ An **ImageBitmap** object stores pixel data rendered on a canvas. ...@@ -33,7 +33,7 @@ An **ImageBitmap** object stores pixel data rendered on a canvas.
.height('100%') .height('100%')
.backgroundColor('#ffff00') .backgroundColor('#ffff00')
.onReady(() =>{ .onReady(() =>{
this.context.drawImage( this.img,0,0,500,500,0,0,400,200); this.context.drawImage( this.img,0,0,500,500,0,0,400,200)
}) })
} }
.width('100%') .width('100%')
......
...@@ -23,8 +23,8 @@ An **ImageData** object stores pixel data rendered on a canvas. ...@@ -23,8 +23,8 @@ An **ImageData** object stores pixel data rendered on a canvas.
@Entry @Entry
@Component @Component
struct Translate { struct Translate {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private img:ImageBitmap = new ImageBitmap("/common/images/1234.png") private img:ImageBitmap = new ImageBitmap("/common/images/1234.png")
build() { build() {
...@@ -34,9 +34,9 @@ struct Translate { ...@@ -34,9 +34,9 @@ struct Translate {
.height('100%') .height('100%')
.backgroundColor('#ffff00') .backgroundColor('#ffff00')
.onReady(() =>{ .onReady(() =>{
this.context.drawImage(this.img,0,0,130,130); this.context.drawImage(this.img,0,0,130,130)
var imagedata = this.context.getImageData(50,50,130,130); var imagedata = this.context.getImageData(50,50,130,130)
this.context.putImageData(imagedata,150,150); this.context.putImageData(imagedata,150,150)
}) })
} }
.width('100%') .width('100%')
......
...@@ -383,7 +383,7 @@ Draws an arc based on the radius and points on the arc. ...@@ -383,7 +383,7 @@ Draws an arc based on the radius and points on the arc.
## ellipse ## ellipse
ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, counterclockwise?: number): void ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void
Draws an ellipse in the specified rectangular region on the canvas. Draws an ellipse in the specified rectangular region on the canvas.
...@@ -398,7 +398,7 @@ Draws an ellipse in the specified rectangular region on the canvas. ...@@ -398,7 +398,7 @@ Draws an ellipse in the specified rectangular region on the canvas.
| rotation | number | Yes| 0 | Rotation angle of the ellipse. The unit is radian.| | rotation | number | Yes| 0 | Rotation angle of the ellipse. The unit is radian.|
| startAngle | number | Yes| 0 | Angle of the start point for drawing the ellipse. The unit is radian.| | startAngle | number | Yes| 0 | Angle of the start point for drawing the ellipse. The unit is radian.|
| endAngle | number | Yes| 0 | Angle of the end point for drawing the ellipse. The unit is radian.| | endAngle | number | Yes| 0 | Angle of the end point for drawing the ellipse. The unit is radian.|
| counterclockwise | number | No| 0 | Whether to draw the ellipse counterclockwise. The value **0** means to draw the ellipse clockwise, and **1** means to draw the ellipse counterclockwise. This parameter is optional. The default value is **0**.| | counterclockwise | boolean | No| false | Whether to draw the ellipse counterclockwise.<br>**true**: Draw the ellipse counterclockwise.<br>**false**: Draw the ellipse clockwise.|
**Example** **Example**
......
...@@ -65,10 +65,10 @@ struct MyComponent { ...@@ -65,10 +65,10 @@ struct MyComponent {
}, },
}) })
.onConnect(() => { .onConnect(() => {
console.log('AbilityComponent connect'); console.log('AbilityComponent connect')
}) })
.onDisconnect(() => { .onDisconnect(() => {
console.log('AbilityComponent disconnect'); console.log('AbilityComponent disconnect')
}) })
} }
} }
......
# Counter # Counter
The **\<Counter>** component provides an operation to increase or decrease the number.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Counter>** component provides an operation to increase or decrease the number.
## Required Permissions ## Required Permissions
None None
...@@ -29,8 +28,8 @@ The universal events and gestures are not supported. Only the following events a ...@@ -29,8 +28,8 @@ The universal events and gestures are not supported. Only the following events a
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onInc(event: () =&gt; void) | Invoked when the number of monitored objects is increased. | | onInc(event: () =&gt; void) | Invoked when the number of monitored objects is increased.|
| onDec(event: () =&gt; void) | Invoked when the number of monitored objects is decreased. | | onDec(event: () =&gt; void) | Invoked when the number of monitored objects is decreased.|
## Example ## Example
......
# ListItemGroup # ListItemGroup
The **\<ListItemGroup>** component is used to display list item groups. It must be used with the **[\<List>](ts-container-list.md)** and, if not otherwise specified, takes up the entire width of the **\<List>** component. The **\<ListItemGroup>** component is used to display list item groups. It must be used with the **[\<List>](ts-container-list.md)** component and, if not otherwise specified, takes up the entire width of the **\<List>**.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. > - This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
## Usage Guidelines ## Usage Guidelines
If the **listDirection** attribute of the parent **\<List>** component is set to **Axis.Vertical**, the **height** attribute of the **\<ListItemGroup>** component cannot be set. The height of a **\<ListItemGroup>** component is the sum of its header height, footer height, and total height of the list items. If the **listDirection** attribute of the parent **\<List>** component is set to **Axis.Horizontal**, the **width** attribute of the **\<ListItemGroup>** component cannot be set. The width of a **\<ListItemGroup>** component is the sum of its header width, footer width, and total width of the list items. If the **listDirection** attribute of the parent **\<List>** component is set to **Axis.Vertical**, the **height** attribute of the **\<ListItemGroup>** component cannot be set. The height of a **\<ListItemGroup>** component is the sum of its header height, footer height, and total height of the list items. If the **listDirection** attribute of the parent **\<List>** component is set to **Axis.Horizontal**, the **width** attribute of the **\<ListItemGroup>** component cannot be set. The width of a **\<ListItemGroup>** component is the sum of its header width, footer width, and total width of the list items.
...@@ -31,7 +31,7 @@ ListItemGroup(options?: {header?: CustomBuilder, footer?: CustomBuilder, space?: ...@@ -31,7 +31,7 @@ ListItemGroup(options?: {header?: CustomBuilder, footer?: CustomBuilder, space?:
| Name| Type| Description| | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| divider | {<br>strokeWidth: [Length](ts-types.md#length),<br>color?: [ResourceColor](ts-types.md#resourcecolor),<br>startMargin?: [Length](ts-types.md#length),<br>endMargin?: [Length](ts-types.md#length)<br>} \| null | Style of the divider for the list items. By default, there is no divider.<br>- **strokeWidth**: stroke width of the divider.<br>- **color**: color of the divider.<br>**startMargin**: distance between the divider and the start of the list.<br>**endMargin**: distance between the divider and the end of the list.| | divider | {<br>strokeWidth: [Length](ts-types.md#length),<br>color?: [ResourceColor](ts-types.md#resourcecolor),<br>startMargin?: [Length](ts-types.md#length),<br>endMargin?: [Length](ts-types.md#length)<br>} \| null | Style of the divider for the list items. By default, there is no divider.<br>- **strokeWidth**: stroke width of the divider.<br>- **color**: color of the divider.<br>- **startMargin**: distance between the divider and the start of the list.<br>- **endMargin**: distance between the divider and the end of the list.|
## Example ## Example
...@@ -51,7 +51,7 @@ function itemHeadBuilder(text: string) { ...@@ -51,7 +51,7 @@ function itemHeadBuilder(text: string) {
function itemFootBuilder(num: number) { function itemFootBuilder(num: number) {
@Builder function itemFoot() { @Builder function itemFoot() {
Text('' + num + " lessons in total ") Text(''Total lessons:'+ num")
.fontSize(16) .fontSize(16)
.backgroundColor(0xAABBCC) .backgroundColor(0xAABBCC)
.width("100%") .width("100%")
...@@ -96,7 +96,7 @@ struct ListItemGroupExample { ...@@ -96,7 +96,7 @@ struct ListItemGroupExample {
}, item => item) }, item => item)
} }
.borderRadius(20) .borderRadius(20)
.divider({ strokeWidth: 1, color: 0xDCDCDC }) // Divider between lines .divider ({ strokeWidth: 1,color:Color.Blue }) // Divider between lines
}) })
} }
.width('90%') .width('90%')
...@@ -106,4 +106,4 @@ struct ListItemGroupExample { ...@@ -106,4 +106,4 @@ struct ListItemGroupExample {
} }
``` ```
![en-us_image_0000001219864159](figures/en-us_image_listitemgroup.gif)
...@@ -25,7 +25,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -25,7 +25,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name | Type | Description | | Name | Type | Description |
| -------------- | ---------------------------------------- | --------- | | -------------- | ---------------------------------------- | --------- |
| scrollable | [ScrollDirection](#scrolldirection) | Scroll direction.<br>Default value: **ScrollDirection.Vertical**| | scrollable | [ScrollDirection](#scrolldirection) | Scroll direction.<br>Default value: **ScrollDirection.Vertical**|
| scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.<br>Default value: **BarState.Off**| | scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.<br>Default value: **BarState.Auto**|
| scrollBarColor | string \| number \| [Color](ts-appendix-enums.md#color) | Color of the scrollbar.| | scrollBarColor | string \| number \| [Color](ts-appendix-enums.md#color) | Color of the scrollbar.|
| scrollBarWidth | string \| number | Width of the scrollbar.| | scrollBarWidth | string \| number | Width of the scrollbar.|
| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. For details, see **EdgeEffect**.<br>Default value: **EdgeEffect.None**| | edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. For details, see **EdgeEffect**.<br>Default value: **EdgeEffect.None**|
...@@ -36,7 +36,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -36,7 +36,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Horizontal | Only horizontal scrolling is supported. | | Horizontal | Only horizontal scrolling is supported. |
| Vertical | Only vertical scrolling is supported. | | Vertical | Only vertical scrolling is supported. |
| None | Scrolling is disabled. | | None | Scrolling is disabled. |
| Free<sup>(deprecated) </sup> | Vertical or horizontal scrolling is supported.<br>This API is deprecated since API version 9. | | Free<sup>(deprecated) </sup> | Vertical or horizontal scrolling is supported.<br> This API is deprecated since API version 9.|
## Events ## Events
...@@ -104,7 +104,7 @@ Scrolls to the next or previous page. ...@@ -104,7 +104,7 @@ Scrolls to the next or previous page.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------- | ---- | ------------------------------ | | --------- | ------- | ---- | ------------------------------ |
| next | boolean | Yes | Whether to turn to the next page. The value **true** means to scroll to the next page, and **false** means to scroll to the previous page.| | next | boolean | Yes | Whether to turn to the next page. The value **true** means to scroll to the next page, and **false** means to scroll to the previous page.|
| direction<sup>(deprecated) </sup> | [Axis](ts-appendix-enums.md#axis) | No | Scrolling direction: horizontal or vertical.<br>This API is deprecated since API version 9. | | direction<sup>(deprecated) </sup> | [Axis](ts-appendix-enums.md#axis) | No | Scrolling direction: horizontal or vertical.<br> This API is deprecated since API version 9. |
### currentOffset ### currentOffset
...@@ -168,8 +168,8 @@ Scrolls by the specified amount. ...@@ -168,8 +168,8 @@ Scrolls by the specified amount.
@Entry @Entry
@Component @Component
struct ScrollExample { struct ScrollExample {
scroller: Scroller = new Scroller(); scroller: Scroller = new Scroller()
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
build() { build() {
Stack({ alignContent: Alignment.TopStart }) { Stack({ alignContent: Alignment.TopStart }) {
...@@ -193,33 +193,33 @@ struct ScrollExample { ...@@ -193,33 +193,33 @@ struct ScrollExample {
.scrollBarWidth(30) // Width of the scrollbar. .scrollBarWidth(30) // Width of the scrollbar.
.edgeEffect(EdgeEffect.None) .edgeEffect(EdgeEffect.None)
.onScroll((xOffset: number, yOffset: number) => { .onScroll((xOffset: number, yOffset: number) => {
console.info(xOffset + ' ' + yOffset); console.info(xOffset + ' ' + yOffset)
}) })
.onScrollEdge((side: Edge) => { .onScrollEdge((side: Edge) => {
console.info('To the edge'); console.info('To the edge')
}) })
.onScrollEnd(() => { .onScrollEnd(() => {
console.info('Scroll Stop'); console.info('Scroll Stop')
}) })
Button('scroll 150') Button('scroll 150')
.onClick(() => { // Click to scroll down to 150.0 vp. .onClick(() => { // Click to scroll down to 150.0 vp.
this.scroller.scrollBy(0,150); this.scroller.scrollBy(0,150)
}) })
.margin({ top: 10, left: 20 }) .margin({ top: 10, left: 20 })
Button('scroll 100') Button('scroll 100')
.onClick(() => { // Click to scroll down by 100.0 vp. .onClick(() => { // Click to scroll down by 100.0 vp.
this.scroller.scrollTo({ xOffset: 0, yOffset: this.scroller.currentOffset().yOffset + 100 }); this.scroller.scrollTo({ xOffset: 0, yOffset: this.scroller.currentOffset().yOffset + 100 })
}) })
.margin({ top: 60, left: 20 }) .margin({ top: 60, left: 20 })
Button('back top') Button('back top')
.onClick(() => { // Click to go back to the top. .onClick(() => { // Click to go back to the top.
this.scroller.scrollEdge(Edge.Top); this.scroller.scrollEdge(Edge.Top)
}) })
.margin({ top: 110, left: 20 }) .margin({ top: 110, left: 20 })
Button('next page') Button('next page')
.onClick(() => { // Click to go to the next page. .onClick(() => { // Click to go to the next page.
this.scroller.scrollPage({ next: true }); this.scroller.scrollPage({ next: true })
}) })
.margin({ top: 170, left: 20 }) .margin({ top: 170, left: 20 })
}.width('100%').height('100%').backgroundColor(0xDCDCDC) }.width('100%').height('100%').backgroundColor(0xDCDCDC)
...@@ -235,8 +235,8 @@ struct ScrollExample { ...@@ -235,8 +235,8 @@ struct ScrollExample {
@Component @Component
struct NestedScroll { struct NestedScroll {
@State listPosition: number = 0; // 0 indicates scrolling to the top of the list, 1 indicates scrolling to the middle of the list, and 2 indicates scrolling to the bottom of the list. @State listPosition: number = 0; // 0 indicates scrolling to the top of the list, 1 indicates scrolling to the middle of the list, and 2 indicates scrolling to the bottom of the list.
private arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; private arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
private scroller: Scroller = new Scroller(); private scroller: Scroller = new Scroller()
build() { build() {
Flex() { Flex() {
...@@ -257,17 +257,17 @@ struct NestedScroll { ...@@ -257,17 +257,17 @@ struct NestedScroll {
} }
.width("100%").height("50%").edgeEffect(EdgeEffect.None) .width("100%").height("50%").edgeEffect(EdgeEffect.None)
.onReachStart(() => { .onReachStart(() => {
this.listPosition = 0; this.listPosition = 0
}) })
.onReachEnd(() => { .onReachEnd(() => {
this.listPosition = 2; this.listPosition = 2
}) })
.onScrollBegin((dx: number, dy: number) => { .onScrollBegin((dx: number, dy: number) => {
if ((this.listPosition == 0 && dy >= 0) || (this.listPosition == 2 && dy <= 0)) { if ((this.listPosition == 0 && dy >= 0) || (this.listPosition == 2 && dy <= 0)) {
this.scroller.scrollBy(0, -dy); this.scroller.scrollBy(0, -dy)
return { dxRemain: dx, dyRemain: 0 }; return { dxRemain: dx, dyRemain: 0 }
} }
this.listPosition = 1; this.listPosition = 1
return { dxRemain: dx, dyRemain: dy }; return { dxRemain: dx, dyRemain: dy };
}) })
......
...@@ -14,7 +14,7 @@ The **\<Shape>** component is the parent component of the drawing components. Th ...@@ -14,7 +14,7 @@ The **\<Shape>** component is the parent component of the drawing components. Th
## Child Components ## Child Components
This component can contain child components. The following child components are supported: **[\<Rect>](ts-drawing-components-rect.md)**, **[\<Path>](ts-drawing-components-path.md)**, **[\<Circle>](ts-drawing-components-circle.md)**, **[\<Ellipse>](ts-drawing-components-ellipse.md)**, **[\<Polyline>](ts-drawing-components-polyline.md)**, **[\<Polygon>](ts-drawing-components-polygon.md)**, **[\<Image>](ts-basic-components-image.md)**, **[\<Text>](ts-basic-components-text.md)**, **[\<Column>](ts-container-column.md)**, and **[\<Row>](ts-container-row.md)**.
## APIs ## APIs
...@@ -22,94 +22,214 @@ This component can contain child components. ...@@ -22,94 +22,214 @@ This component can contain child components.
Shape(value?: PixelMap) Shape(value?: PixelMap)
**Parameters** **Parameters**
| Name| Type| Mandatory| Default Value| Description| | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| value | PixelMap | No| - | Shape to draw. You can draw a shape in the specified **PixelMap** object. If no object is specified, the shape is drawn in the current drawing target.| | value | [PixelMap](../apis/js-apis-image.md#pixelmap7) | No| - | Shape to draw. You can draw a shape in the specified **PixelMap** object. If no object is specified, the shape is drawn in the current drawing target.|
## Attributes ## Attributes
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name| Type| Default Value| Mandatory| Description| | Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| viewPort | {<br>x?: number \| string,<br>y?: number \| string,<br>width?: number \| string,<br>height?: number \| string<br>} | { x:0, y:0, width:0, height:0 } | No| View port of the shape.| | viewPort | {<br>x?: number \| string,<br>y?: number \| string,<br>width?: number \| string,<br>height?: number \| string<br>} | { x:0, y:0, width:0, height:0 } | View port of the shape.|
| fill | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Color of the fill area.| | fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.|
| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | No| Opacity of the fill area.| | fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.|
| stroke | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Stroke color.| | stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, no stroke is displayed.|
| strokeDashArray | Array&lt;Length&gt; | [] | No| Stroke dash.| | strokeDashArray | Array&lt;Length&gt; | [] | Stroke dashes.|
| strokeDashOffset | number \| string | 0 | No| Offset of the start point for drawing the stroke.| | strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | No| Cap style of the stroke.| | strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | No| Join style of the stroke.| | strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.|
| strokeMiterLimit | number \| string | 4 | No| Limit value when the sharp angle is drawn as a miter.| | strokeMiterLimit | number \| string | 4 | Limit value when the sharp angle is drawn as a miter.|
| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | No| Stroke opacity.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.<br>**NOTE**<br>The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.|
| strokeWidth | number \| string | 1 | No| Stroke width.| | strokeWidth | number \| string | 1 | Stroke width.|
| antiAlias | boolean | true | No| Whether anti-aliasing is enabled.| | antiAlias | boolean | true | Whether anti-aliasing is enabled.|
| mesh<sup>8+</sup> | Array&lt;number&gt;,number,number | [],0,0 | No| Mesh effect. The first parameter is an array of lengths (column + 1) * (row + 1) * 2, which records the position of each vertex of the distorted bitmap. The second parameter is the number of columns in the mesh matrix. The third parameter is the number of rows in the mesh matrix.| | mesh<sup>8+</sup> | Array&lt;number&gt;,number,number | [],0,0 | Mesh effect. The first parameter is an array of lengths (column + 1) * (row + 1) * 2, which records the position of each vertex of the distorted bitmap. The second parameter is the number of columns in the mesh matrix. The third parameter is the number of rows in the mesh matrix.|
## Example ## Example
### Example 1
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct ShapeExample { struct ShapeExample {
build() { build() {
Column({ space: 5 }) { Column({ space: 10 }) {
Text('basic').fontSize(30).fontColor(0xCCCCCC).width(320) Text('basic').fontSize(11).fontColor(0xCCCCCC).width(320)
// Draw a 300 x 50 rectangle with strokes at (-2, -2). The fill color is 0x317Af7, the stroke color is black, the stroke width is 4, the stroke dash is 20, the offset is 10 to the left, the cap style is rounded, the join style is rounded, and anti-aliasing is enabled (default). // Draw a 300 x 50 rectangle with strokes at (-2, -2). The fill color is 0x317AF7, the stroke color is black, the stroke width is 4, the stroke dash is 20, the offset is 10 to the left, the cap style is rounded, the join style is rounded, and anti-aliasing is enabled (default).
// Draw a 300 x 50 ellipse with strokes at (-2, 58). The fill color is 0x317Af7, the stroke color is black, the stroke width is 4, the stroke dash is 20, the offset is 10 to the left, the cap style is rounded, the join style is rounded, and anti-aliasing is enabled (default). // Draw a 300 x 50 ellipse with strokes at (-2, 58). The fill color is 0x317AF7, the stroke color is black, the stroke width is 4, the stroke dash is 20, the offset is 10 to the left, the cap style is rounded, the join style is rounded, and anti-aliasing is enabled (default).
// Draw a 300 x 10 path at (-2, 118). The fill color is 0x317Af7, the stroke color is black, the stroke width is 4, the stroke dash is 20, the offset is 10 to the left, the cap style is rounded, the join style is rounded, and anti-aliasing is enabled (default). // Draw a 300 x 10 straight line at (-2, 118). The fill color is 0x317AF7, the stroke color is black, the stroke width is 4, the stroke dash is 20, the offset is 10 to the left, the cap style is rounded, the join style is rounded, and anti-aliasing is enabled (default).
Shape() { Shape() {
Rect().width(300).height(50) Rect().width(300).height(50)
Ellipse().width(300).height(50).offset({ x: 0, y: 60 }) Ellipse().width(300).height(50).offset({ x: 0, y: 60 })
Path().width(300).height(10).commands('M0 0 L900 0').offset({ x: 0, y: 120 }) Path().width(300).height(10).commands('M0 0 L900 0').offset({ x: 0, y: 120 })
} }
.viewPort({ x: -2, y: -2, width: 304, height: 130 }) .viewPort({ x: -2, y: -2, width: 304, height: 130 })
.fill(0x317Af7).stroke(Color.Black).strokeWidth(4) .fill(0x317AF7)
.strokeDashArray([20]).strokeDashOffset(10).strokeLineCap(LineCapStyle.Round) .stroke(Color.Black)
.strokeLineJoin(LineJoinStyle.Round).antiAlias(true) .strokeWidth(4)
// Draw a 300 x 50 rectangle with strokes at (-1, -1). The fill color is 0x317Af7, the stroke color is black, and the stroke width is 2. .strokeDashArray([20])
.strokeDashOffset(10)
.strokeLineCap(LineCapStyle.Round)
.strokeLineJoin(LineJoinStyle.Round)
.antiAlias(true)
// Draw a 300 x 50 rectangle with strokes at (0, 0) and (-5, -5). The drawing start point is the midpoint of the stroke width by default. To fully display the strokes, you must set the coordinates of the start position of the viewport to negative values so that the viewport is offset by half the stroke width.
Shape() { Shape() {
Rect().width(300).height(50) Rect().width(300).height(50)
}.viewPort({ x: -1, y: -1, width: 302, height: 52 }).fill(0x317Af7).stroke(Color.Black).strokeWidth(2) }
.viewPort({ x: 0, y: 0, width: 320, height: 70 })
.fill(0x317AF7)
.stroke(Color.Black)
.strokeWidth(10)
Text('border').fontSize(30).fontColor(0xCCCCCC).width(320).margin({top:30})
// Draw a 300 x 10 path at (0, -5). The color is 0xEE8443, the stroke width is 10, and the stroke gap is 20.
Shape() { Shape() {
Path().width(300).height(10).commands('M0 0 L900 0') Rect().width(300).height(50)
}.viewPort({ x: 0, y: -5, width: 300, height: 20 }).stroke(0xEE8443).strokeWidth(10).strokeDashArray([20]) }
// Draw a 300 x 10 path at (0, -5). The fill color is 0xEE8443, the stroke width is 10, the stroke dash is 20, and the offset is 10 to the left. .viewPort({ x: -5, y: -5, width: 320, height: 70 })
.fill(0x317AF7)
.stroke(Color.Black)
.strokeWidth(10)
Text('path').fontSize(11).fontColor(0xCCCCCC).width(320)
// Draw a straight line at (0, -5). The fill color is 0xEE8443, the stroke width is 10, and the stroke dash is 20.
Shape() { Shape() {
Path().width(300).height(10).commands('M0 0 L900 0') Path().width(300).height(10).commands('M0 0 L900 0')
} }
.viewPort({ x: 0, y: -5, width: 300, height: 20 }) .viewPort({ x: 0, y: -5, width: 300, height: 20 })
.stroke(0xEE8443).strokeWidth(10).strokeDashArray([20]).strokeDashOffset(10) .stroke(0xEE8443)
// Draw a 300 x 10 path at (0, -5). The fill color is 0xEE8443, the stroke width is 10, and the stroke opacity is 0.5. .strokeWidth(10)
.strokeDashArray([20])
// Draw a straight line at (0, -5). The fill color is 0xEE8443, the stroke width is 10, the stroke dash is 20, and the offset is 10 to the left.
Shape() { Shape() {
Path().width(300).height(10).commands('M0 0 L900 0') Path().width(300).height(10).commands('M0 0 L900 0')
}.viewPort({ x: 0, y: -5, width: 300, height: 20 }).stroke(0xEE8443).strokeWidth(10).strokeOpacity(0.5) }
// Draw a 300 x 10 path at (0, -5). The fill color is 0xEE8443, the stroke width is 10, the stroke dash is 20, the offset is 10 to the left, and the cap style is rounded. .viewPort({ x: 0, y: -5, width: 300, height: 20 })
.stroke(0xEE8443)
.strokeWidth(10)
.strokeDashArray([20])
.strokeDashOffset(10)
// Draw a straight line at (0, -5). The fill color is 0xEE8443, the stroke width is 10, and the stroke opacity is 0.5.
Shape() { Shape() {
Path().width(300).height(10).commands('M0 0 L900 0') Path().width(300).height(10).commands('M0 0 L900 0')
} }
.viewPort({ x: 0, y: -5, width: 300, height: 20 }) .viewPort({ x: 0, y: -5, width: 300, height: 20 })
.stroke(0xEE8443).strokeWidth(10).strokeDashArray([20]).strokeLineCap(LineCapStyle.Round) .stroke(0xEE8443)
// Draw a 300 x 50 rectangle with strokes at (-5, -5). The fill color is 0x317Af7, the stroke width is 10, the stroke color is 0xEE8443, and the join style is rounded. .strokeWidth(10)
.strokeOpacity(0.5)
// Draw a straight line at (0, -5). The fill color is 0xEE8443, the stroke width is 10, the stroke dash is 20, and the cap style is rounded.
Shape() { Shape() {
Rect().width(300).height(100) Path().width(300).height(10).commands('M0 0 L900 0')
} }
.viewPort({ x: -5, y: -5, width: 310, height: 120 }) .viewPort({ x: 0, y: -5, width: 300, height: 20 })
.fill(0x317Af7).stroke(0xEE8443).strokeWidth(10).strokeLineJoin(LineJoinStyle.Round) .stroke(0xEE8443)
.strokeWidth(10)
.strokeDashArray([20])
.strokeLineCap(LineCapStyle.Round)
// Draw a closed path at (-80, -5). The fill color is 0x317AF7, the stroke width is 10, the stroke color is 0xEE8443, and the join style is miter (default value).
Shape() { Shape() {
Path().width(300).height(60).commands('M0 0 L400 0 L400 200 Z') Path().width(200).height(60).commands('M0 0 L400 0 L400 150 Z')
} }
.viewPort({ x: -80, y: -5, width: 310, height: 100 }) .viewPort({ x: -80, y: -5, width: 310, height: 90 })
.fill(0x317Af7).stroke(0xEE8443).strokeWidth(10) .fill(0x317AF7)
.strokeLineJoin(LineJoinStyle.Miter).strokeMiterLimit(5) .stroke(0xEE8443)
.strokeWidth(10)
.strokeLineJoin(LineJoinStyle.Miter)
.strokeMiterLimit(5)
}.width('100%').margin({ top: 15 }) }.width('100%').margin({ top: 15 })
} }
} }
``` ```
![en-us_image_0000001257058393](figures/en-us_image_0000001257058393.png) ![en-us_image_0000001184628104](figures/en-us_image_0000001184628104.png)
### Example 2
```ts
// xxx.ets
@Entry
@Component
struct ShapeMeshExample {
@State columnVal: number = 0
@State rowVal: number = 0
@State count: number = 0
@State verts: Array<number> = []
@State shapeWidth: number = 600
@State shapeHeight: number = 600
build() {
Column() {
Shape() {
Rect()
.width('250px')
.height('250px')
.radiusWidth('10px')
.radiusHeight('10px')
.stroke('10px')
.margin({ left: '10px', top: '10px' })
.strokeWidth('10px')
.fill(Color.Blue)
Rect()
.width('250px')
.height('250px')
.radiusWidth('10px')
.radiusHeight('10px')
.stroke('10px')
.margin({ left: '270px', top: '10px' })
.strokeWidth('10px')
.fill(Color.Red)
}
.mesh(this.verts, this.columnVal, this.rowVal)
.width(this.shapeWidth + 'px')
.height(this.shapeHeight + 'px')
// The mesh distortion effect is displayed when the component is touched.
.onTouch((event: TouchEvent) => {
var touchX = event.touches[0].x * 2
var touchY = event.touches[0].y * 2
this.columnVal = 20
this.rowVal = 20
this.count = (this.columnVal + 1) * (this.rowVal + 1)
var orig = [this.count * 2]
var index = 0
for (var i = 0; i <= this.rowVal; i++) {
var fy = this.shapeWidth * i / this.rowVal
for (var j = 0; j <= this.columnVal; j++) {
var fx = this.shapeWidth * j / this.columnVal
orig[index * 2 + 0] = this.verts[index * 2 + 0] = fx
orig[index * 2 + 1] = this.verts[index * 2 + 1] = fy
index++;
}
}
for (var k = 0; k < this.count * 2; k += 2) {
var dx = touchX - orig[k + 0]
var dy = touchY - orig[k + 1]
var dd = dx * dx + dy * dy
var d = Math.sqrt(dd)
var pull = 80000 / (dd * d)
if (pull >= 1) {
this.verts[k + 0] = touchX
this.verts[k + 1] = touchY
} else {
this.verts[k + 0] = orig[k + 0] + dx * pull
this.verts[k + 1] = orig[k + 1] + dy * pull
}
}
})
}
.width('600px')
.height('600px')
.border({ width: 3, color: Color.Black })
}
}
```
Below is how the component is displayed when not being touched.
![en-us_image1_0000001184628104](figures/en-us_image1_0000001184628104.png)
The mesh distortion effect is displayed when the component is touched, as shown below.
![en-us_image2_0000001184628104](figures/en-us_image2_0000001184628104.png)
...@@ -7,83 +7,75 @@ Bind different types of gesture events to components and set response methods fo ...@@ -7,83 +7,75 @@ Bind different types of gesture events to components and set response methods fo
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Binding Gesture Recognition ## Binding Gesture Recognition
Use the following attributes to bind gesture recognition to a component. When a gesture is recognized, the event callback is invoked to notify the component. Use the following attributes to bind gesture recognition to a component. When a gesture is recognized, the event callback is invoked to notify the component.
| Name| Type| Default Value| Description|
| Parameter| Type| Default Value| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| gesture | gesture: GestureType,<br>mask?: GestureMask | gesture: -,<br>mask: GestureMask.Normal | Gesture to recognize.<br>- **gesture**: type of the gesture to bind.<br>- **mask**: event response setting.| | gesture | gesture: [GestureType](#gesturetype),<br>mask?: [GestureMask](#gesturemask) | gesture: -,<br>mask: GestureMask.Normal | Gesture to bind.<br>- **gesture**: type of the gesture to bind.<br>- **mask**: event response setting.|
| priorityGesture | gesture: GestureType,<br>mask?: GestureMask | gesture: -,<br>mask: GestureMask.Normal | Gesture to preferentially recognize.<br>- **gesture**: type of the gesture to bind.<br>- **mask**: event response setting.<br>By default, the child component takes precedence over the parent component in gesture recognition. When **priorityGesture** is configured for the parent component, the parent component takes precedence over the child component in gesture recognition.| | priorityGesture | gesture: [GestureType](#gesturetype),<br>mask?: [GestureMask](#gesturemask) | gesture: -,<br>mask: GestureMask.Normal | Gesture to preferentially recognize.<br>- **gesture**: type of the gesture to bind.<br>- **mask**: event response setting.<br>By default, a component recognizes gestures bound through **gesture**. When **priorityGesture** is configured for its parent component, the component preferentially recognizes gestures bound through **priorityGesture**.|
| parallelGesture | gesture: GestureType,<br>mask?: GestureMask | gesture: -,<br>mask: GestureMask.Normal | Gesture that can be triggered together with the child component gesture.<br>- **gesture**: type of the gesture to bind. <br>- **mask**: event response setting.<br>The gesture event is not a bubbling event. When **parallelGesture** is set for the parent component, gesture events that are the same for the parent component and child components can be triggered, thereby implementing a bubbling effect.| | parallelGesture | gesture: [GestureType](#gesturetype),<br>mask?: [GestureMask](#gesturemask) | gesture: -,<br>mask: GestureMask.Normal | Gesture that can be triggered together with the child component gesture.<br>- **gesture**: type of the gesture to bind. <br>- **mask**: event response setting.<br>The gesture event is not a bubbling event. When **parallelGesture** is set for the parent component, gesture events that are the same for the parent component and child components can be triggered, thereby implementing a bubbling effect.|
- GestureMask ## GestureType
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| Normal | The gestures of child components are not masked and are recognized based on the default gesture recognition sequence.| | [TapGesture](ts-basic-gestures-tapgesture.md) | Tap gesture, which can be a single-tap or multi-tap gesture.|
| IgnoreInternal | The gestures of child components are masked. Only the gestures of the current component are recognized.<br>However, the built-in gestures of the child components are not masked. For example, when the child component is a **\<List>** component, the built-in sliding gestures can still be triggered.| | [LongPressGesture](ts-basic-gestures-longpressgesture.md) | Long press gesture.|
| [PanGesture](ts-basic-gestures-pangesture.md) | Pan gesture, which requires a minimum 5 vp movement distance of a finger on the screen.|
| [PinchGesture](ts-basic-gestures-pinchgesture.md) | Pinch gesture.|
| [RotationGesture](ts-basic-gestures-rotationgesture.md) | Rotation gesture.|
| [SwipeGesture](ts-basic-gestures-swipegesture.md) | Swipe gesture, which can be recognized when the swipe speed is 100 vp/s or higher.|
| [GestureGroup](ts-combined-gestures.md) | A group of gestures. Continuous recognition, parallel recognition, and exclusive recognition are supported.|
- GestureType ## GestureMask
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| TapGesture | Tap gesture, which can be a single-tap or multi-tap gesture.| | Normal | The gestures of child components are not ignored and are recognized based on the default gesture recognition sequence.|
| LongPressGesture | Long press gesture.| | IgnoreInternal | The gestures of child components are ignored. Only the gestures of the current component are recognized.<br>However, the built-in gestures of the child components are not ignored. For example, when the child component is a **\<List>** component, the built-in sliding gestures can still be triggered.|
| PanGesture | Pan gesture, which requires a minimum 5 vp movement distance of a finger on the screen.|
| PinchGesture | Pinch gesture.|
| RotationGesture | Rotation gesture.|
| SwipeGesture | Swipe gesture, which can be recognized when the swipe speed is 100 vp/s or higher.|
| GestureGroup | A group of gestures. Continuous recognition, parallel recognition, and exclusive recognition are supported.|
## Gesture Response Event ## Gesture Response Event
The component uses the **gesture** method to bind the gesture object and uses the events provided in this object to respond to the gesture operation. For example, the **onAction** event of the **TapGesture** object can be used to respond to a click event. For details about the event definitions of other gestures, see the corresponding gesture sections. The component binds gesture objects of different **GestureType**s through gesture events. Each gesture object provides gesture-related information in the gesture response event. In the following example, the **TapGesture** object provides gesture-related information in the **onAction** event. For details about the event definitions of other gestures, see the corresponding gesture sections. To bind multiple gestures, use [combined gestures](ts-combined-gestures.md).
- TapGesture - TapGesture
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onAction((event?:GestureEvent) =&gt; void) | Callback invoked when a tap gesture is recognized.| | onAction((event?:GestureEvent) =&gt; void) | Callback invoked when a tap gesture is recognized.|
- GestureEvent attributes ## GestureEvent
| Name| Type| Description| | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| timestamp<sup>8+</sup> | number | Timestamp of the event. It is interval between the time when the event is triggered and the time when the system starts, in nanoseconds.| | repeat | boolean | Whether the event is triggered repeatedly. This attribute is used for the **LongPressGesture** event. |
| target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md) | Display area of the element that triggers the gesture event.| | offsetX | number | Offset of the gesture event on the x-axis, in vp. This attribute is used for the **PanGesture** event. A positive value means panning from left to right, and a negative value means the opposite. |
| source<sup>8+</sup> | SourceType | Event input device.| | offsetY | number | Offset of the gesture event on the y-axis, in vp. This attribute is used for the **PanGesture** event. A positive value means panning from top to bottom, and a negative value means the opposite. |
| repeat | boolean | Whether the event is triggered repeatedly. This parameter is used for the **LongPressGesture** event.| | angle | number | Rotation angle for the **RotationGesture** event;<br>angle of the swipe gesture for the **SwipeGesture** event, that is, the change in the included angle between the line segment created by the two fingers and the horizontal direction.<br>**NOTE**<br>Angle calculation method: After a swipe gesture is recognized, a line connecting the two fingers is identified as the initial line. As the fingers swipe, the line between the fingers rotates. Based on the coordinates of the initial line's and current line's end points, an arc tangent function is used to calculate the respective included angle of the points relative to the horizontal direction by using the following formula: Rotation angle = arctan2(cy2-cy1,cx2-cx1) – arctan2(y2-y1,x2-x1) The initial line is used as the coordinate system. The clockwise rotation is 0 to 180 degrees, and the counter-clockwise rotation is –180 to 0 degrees.|
| fingerList<sup>8+</sup> | FingerInfo[] | Information about all fingers that trigger the event, which is used for the **LongPressGesture** and **TapGesture** events.| | scale | number | Scale ratio. This attribute is used for the **PinchGesture** event.|
| offsetX | number | Offset of the gesture event on the x-axis, in vp. This parameter is used for the **PanGesture** event.| | pinchCenterX | number | X-coordinate of the center of the pinch gesture, in px relative to the upper left corner of the current component. This attribute is used for the **PinchGesture** event. |
| offsetY | number | Offset of the gesture event on the y-axis, in vp. This parameter is used for the **PanGesture** event.| | pinchCenterY | number | Y-coordinate of the center of the pinch gesture, in px relative to the upper left corner of the current component. This attribute is used for the **PinchGesture** event. |
| angle | number | Rotation angle for the **RotationGesture** event; angle of the swipe gesture for the **SwipeGesture** event, that is, the change in the included angle between the line segment created by the two fingers and the horizontal direction.<br>**NOTE**<br>Angle calculation method: After a swipe gesture is recognized, a line connecting the two fingers is identified as the initial line. As the fingers swipe, the line between the fingers rotates. Based on the coordinates of the initial line's and current line's end points, an arc tangent function is used to calculate the respective included angle of the points relative to the horizontal direction by using the following formula: Rotation angle = arctan2(cy2-cy1,cx2-cx1) - arctan2(y2-y1,x2-x1) The initial line is used as the coordinate system. The clockwise rotation is 0 to 180 degrees, and the counter-clockwise rotation is –180 to 0 degrees. | | speed<sup>8+</sup> | number | Swipe gesture speed, that is, the average swipe speed of all fingers. The unit is vp/s. This attribute is used for the **SwipeGesture** event.|
| speed<sup>8+</sup> | number | Swipe gesture speed, that is, the average swipe speed of all fingers. The unit is vp/s. This attribute is used for the **SwipeGesture** event.| | fingerList<sup>8+</sup> | [FingerInfo](#fingerinfo)[] | Information about all fingers that trigger the event, which is used for the **LongPressGesture** and **TapGesture** events.|
| scale | number | Scale ratio. This attribute is used for the **PinchGesture** event.| | timestamp<sup>8+</sup> | number | Timestamp of the event.|
| pinchCenterX | number | X-coordinate of the center of the pinch gesture, in px. This attribute is used for the **PinchGesture** event.| | target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md#eventtarget8) | Display area of the element that triggers the gesture event.|
| pinchCenterY | number | Y-coordinate of the center of the pinch gesture, in px. This attribute is used for the **PinchGesture** event.| | source<sup>8+</sup> | [SourceType](#sourcetype) | Event input device.|
- SourceType ## SourceType
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| Unknown | Unknown device type.| | Unknown | Unknown device type.|
| Mouse | Mouse.| | Mouse | Mouse.|
| TouchScreen | Touchscreen.| | TouchScreen | Touchscreen.|
- FingerInfo ## FingerInfo
| Name| Type| Description| | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| id | number | Index of a finger.| | id | number | Index of a finger.|
| globalX | number | X-coordinate relative to the upper left corner of the application window.| | globalX | number | X-coordinate relative to the upper left corner of the application window.|
| globalY | number | Y-coordinate relative to the upper left corner of the application window.| | globalY | number | Y-coordinate relative to the upper left corner of the application window.|
| localX | number | X-coordinate relative to the upper left corner of the current component.| | localX | number | X-coordinate relative to the upper left corner of the current component.|
| localY | number | Y-coordinate relative to the upper left corner of the current component.| | localY | number | Y-coordinate relative to the upper left corner of the current component.|
## Example ## Example
...@@ -93,30 +85,54 @@ The component uses the **gesture** method to bind the gesture object and uses th ...@@ -93,30 +85,54 @@ The component uses the **gesture** method to bind the gesture object and uses th
@Entry @Entry
@Component @Component
struct GestureSettingsExample { struct GestureSettingsExample {
@State value: string = '' @State priorityTestValue: string = ''
@State parallelTestValue: string = ''
build() { build() {
Column(){
Column() { Column() {
Text('Click\n' + this.value) Column() {
Text('TapGesture:' + this.priorityTestValue).fontSize(28)
.gesture( .gesture(
TapGesture() TapGesture()
.onAction(() => { .onAction(() => {
this.value = 'gesture onAction' this.priorityTestValue += '\nText'
})) }))
}.height(200).width(300).padding(60).border({ width: 1 }) }
// When priorityGesture is specified, the bound gesture is preferentially recognized and the child component gesture is ignored. .height(200)
.width(250)
.padding(20)
.margin(20)
.border({ width: 3 })
// When priorityGesture is set, the tap gesture on the <Column> component is prioritized over the tap gesture on the child <Text> component.
.priorityGesture( .priorityGesture(
TapGesture() TapGesture()
.onAction((event: GestureEvent) => { .onAction((event: GestureEvent) => {
this.value = 'priorityGesture onAction' + '\ncomponent globalPos:(' this.priorityTestValue += '\nColumn'
+ event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\nwidth:' }), GestureMask.IgnoreInternal)
+ event.target.area.width + '\nheight:' + event.target.area.height
}), GestureMask.IgnoreInternal Column() {
) Text('TapGesture:' + this.parallelTestValue).fontSize(28)
}.padding(60) .gesture(
TapGesture()
.onAction(() => {
this.parallelTestValue += '\nText'
}))
}
.height(200)
.width(250)
.padding(20)
.margin(20)
.border({ width: 3 })
// When parallelGesture is set, the tap gestures on the <Column> component and on the child <Text> component are both recognized.
.parallelGesture(
TapGesture()
.onAction((event: GestureEvent) => {
this.parallelTestValue += '\nColumn'
}), GestureMask.Normal)
}
} }
} }
``` ```
![en-us_image_0000001257058419](figures/en-us_image_0000001257058419.gif) ![en-us_image_0000001257058419](figures/en-us_image_0000001257058419.gif)
...@@ -24,24 +24,24 @@ OffscreenCanvasRenderingContext2D(width: number, height: number, setting: Render ...@@ -24,24 +24,24 @@ OffscreenCanvasRenderingContext2D(width: number, height: number, setting: Render
## Attributes ## Attributes
| Name | Type | Description | | Name | Type | Description |
| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | | ----------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Style to fill an area.<br>- When the type is **string**, this attribute indicates the color of the filling area.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.| | [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Style to fill an area.<br>- When the type is **string**, this attribute indicates the color of the filling area.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API. |
| [lineWidth](#linewidth) | number | Line width. | | [lineWidth](#linewidth) | number | Line width. |
| [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Stroke style.<br>- When the type is **\<color>**, this parameter indicates the stroke color.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.| | [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Stroke style.<br>- When the type is **\<color>**, this parameter indicates the stroke color.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API. |
| [lineCap](#linecap) | CanvasLineCap | Style of the line endpoints. The options are as follows:<br>- **butt**: The endpoints of the line are squared off.<br>- **round**: The endpoints of the line are rounded.<br>- **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.<br>- Default value: **'butt'**| | [lineCap](#linecap) | CanvasLineCap | Style of the line endpoints. The options are as follows:<br>- **butt**: The endpoints of the line are squared off.<br>- **round**: The endpoints of the line are rounded.<br>- **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.<br>- Default value: **'butt'** |
| [lineJoin](#linejoin) | CanvasLineJoin | Style of the shape used to join line segments. The options are as follows:<br>- **round**: The intersection is a sector, whose radius at the rounded corner is equal to the line width.<br>- **bevel**: The intersection is a triangle. The rectangular corner of each line is independent.<br>- **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**.<br>- Default value: **'miter'**| | [lineJoin](#linejoin) | CanvasLineJoin | Style of the shape used to join line segments. The options are as follows:<br>- **round**: The intersection is a sector, whose radius at the rounded corner is equal to the line width.<br>- **bevel**: The intersection is a triangle. The rectangular corner of each line is independent.<br>- **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**.<br>- Default value: **'miter'** |
| [miterLimit](#miterlimit) | number | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.<br>- Default value: **10**| | [miterLimit](#miterlimit) | number | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.<br>- Default value: **10** |
| [font](#font) | string | Font style.<br>Syntax: ctx.font='font-size font-family'<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>(Optional) **font-family**: font family.<br>Syntax: ctx.font='font-style font-weight font-size font-family'<br>- (Optional) **font-style**: font style. Available values are **normal** and **italic**.<br>- (Optional) **font-weight**: font weight. Available values are as follows: **normal**, **bold**, **bolder**, **lighter**, **100**, **200**, **300**, **400**, **500**, **600**, **700**, **800**, **900**.<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>- (Optional) **font-family**: font family. Available values are **sans-serif**, **serif**, and **monospace**.<br>Default value: **'normal normal 14px sans-serif'**| | [font](#font) | string | Font style.<br>Syntax: ctx.font='font-size font-family'<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>(Optional) **font-family**: font family.<br>Syntax: ctx.font='font-style font-weight font-size font-family'<br>- (Optional) **font-style**: font style. Available values are **normal** and **italic**.<br>- (Optional) **font-weight**: font weight. Available values are as follows: **normal**, **bold**, **bolder**, **lighter**, **100**, **200**, **300**, **400**, **500**, **600**, **700**, **800**, **900**.<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>- (Optional) **font-family**: font family. Available values are **sans-serif**, **serif**, and **monospace**.<br>Default value: **'normal normal 14px sans-serif'** |
| [textAlign](#textalign) | CanvasTextAlign | Text alignment mode. Available values are as follows:<br>- **left**: The text is left-aligned.<br>- **right**: The text is right-aligned.<br>- **center**: The text is center-aligned.<br>- **start**: The text is aligned with the start bound.<br>- **end**: The text is aligned with the end bound.<br>> **NOTE**<br>> In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.<br>- Default value: **'left'**| | [textAlign](#textalign) | CanvasTextAlign | Text alignment mode. Available values are as follows:<br>- **left**: The text is left-aligned.<br>- **right**: The text is right-aligned.<br>- **center**: The text is center-aligned.<br>- **start**: The text is aligned with the start bound.<br>- **end**: The text is aligned with the end bound.<br>**NOTE**<br>In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.<br>- Default value: **'left'** |
| [textBaseline](#textbaseline) | CanvasTextBaseline | Horizontal alignment mode of text. Available values are as follows:<br>- **alphabetic**: The text baseline is the normal alphabetic baseline.<br>- **top**: The text baseline is on the top of the text bounding box.<br>- **hanging**: The text baseline is a hanging baseline over the text.<br>- **middle**: The text baseline is in the middle of the text bounding box.<br>**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.<br>- **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.<br>- Default value: **'alphabetic'**| | [textBaseline](#textbaseline) | CanvasTextBaseline | Horizontal alignment mode of text. Available values are as follows:<br>- **alphabetic**: The text baseline is the normal alphabetic baseline.<br>- **top**: The text baseline is on the top of the text bounding box.<br>- **hanging**: The text baseline is a hanging baseline over the text.<br>- **middle**: The text baseline is in the middle of the text bounding box.<br>**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.<br>- **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.<br>- Default value: **'alphabetic'** |
| [globalAlpha](#globalalpha) | number | Opacity.<br>**0.0**: completely transparent.<br>**1.0**: completely opaque. | | [globalAlpha](#globalalpha) | number | Opacity.<br>**0.0**: completely transparent.<br>**1.0**: completely opaque. |
| [lineDashOffset](#linedashoffset) | number | Offset of the dashed line. The precision is float.<br>- Default value: **0.0**| | [lineDashOffset](#linedashoffset) | number | Offset of the dashed line. The precision is float.<br>- Default value: **0.0** |
| [globalCompositeOperation](#globalcompositeoperation) | string | 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'**.<br>- Default value: **'source-over'**| | [globalCompositeOperation](#globalcompositeoperation) | string | 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'**.<br>- Default value: **'source-over'** |
| [shadowBlur](#shadowblur) | number | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.<br>- Default value: **0.0**| | [shadowBlur](#shadowblur) | number | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.<br>- Default value: **0.0** |
| [shadowColor](#shadowcolor) | string | Shadow color. | | [shadowColor](#shadowcolor) | string | Shadow color. |
| [shadowOffsetX](#shadowoffsetx) | number | X-axis shadow offset relative to the original object. | | [shadowOffsetX](#shadowoffsetx) | number | X-axis shadow offset relative to the original object. |
| [shadowOffsetY](#shadowoffsety) | number | Y-axis shadow offset relative to the original object. | | [shadowOffsetY](#shadowoffsety) | number | Y-axis shadow offset relative to the original object. |
| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.<br>- Default value: **true**| | [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.<br>- Default value: **true** |
> **NOTE** > **NOTE**
> >
...@@ -68,8 +68,8 @@ struct FillStyleExample { ...@@ -68,8 +68,8 @@ struct FillStyleExample {
.onReady(() =>{ .onReady(() =>{
this.offContext.fillStyle = '#0000ff' this.offContext.fillStyle = '#0000ff'
this.offContext.fillRect(20, 160, 150, 100) this.offContext.fillRect(20, 160, 150, 100)
var image = this.offContext.transferToImageBitmap(); var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image); this.context.transferFromImageBitmap(image)
}) })
} }
.width('100%') .width('100%')
...@@ -446,8 +446,8 @@ struct LineDashOffset { ...@@ -446,8 +446,8 @@ struct LineDashOffset {
.onReady(() =>{ .onReady(() =>{
this.offContext.arc(100, 75, 50, 0, 6.28) this.offContext.arc(100, 75, 50, 0, 6.28)
this.offContext.setLineDash([10,20]) this.offContext.setLineDash([10,20])
this.offContext.lineDashOffset = 10.0; this.offContext.lineDashOffset = 10.0
this.offContext.stroke(); this.offContext.stroke()
var image = this.offContext.transferToImageBitmap() var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image) this.context.transferFromImageBitmap(image)
}) })
...@@ -1374,10 +1374,10 @@ Draws a quadratic curve on the canvas. ...@@ -1374,10 +1374,10 @@ Draws a quadratic curve on the canvas.
.height('100%') .height('100%')
.backgroundColor('#ffff00') .backgroundColor('#ffff00')
.onReady(() =>{ .onReady(() =>{
this.offContext.beginPath(); this.offContext.beginPath()
this.offContext.moveTo(20, 20); this.offContext.moveTo(20, 20)
this.offContext.quadraticCurveTo(100, 100, 200, 20); this.offContext.quadraticCurveTo(100, 100, 200, 20)
this.offContext.stroke(); this.offContext.stroke()
var image = this.offContext.transferToImageBitmap() var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image) this.context.transferFromImageBitmap(image)
}) })
...@@ -1476,9 +1476,9 @@ Draws an arc based on the radius and points on the arc. ...@@ -1476,9 +1476,9 @@ Draws an arc based on the radius and points on the arc.
.height('100%') .height('100%')
.backgroundColor('#ffff00') .backgroundColor('#ffff00')
.onReady(() =>{ .onReady(() =>{
this.offContext.moveTo(100, 20); this.offContext.moveTo(100, 20)
this.offContext.arcTo(150, 20, 150, 70, 50); this.offContext.arcTo(150, 20, 150, 70, 50)
this.offContext.stroke(); this.offContext.stroke()
var image = this.offContext.transferToImageBitmap() var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image) this.context.transferFromImageBitmap(image)
}) })
...@@ -1509,7 +1509,7 @@ Draws an ellipse in the specified rectangular region on the canvas. ...@@ -1509,7 +1509,7 @@ Draws an ellipse in the specified rectangular region on the canvas.
| rotation | number | Yes | 0 | Rotation angle of the ellipse. The unit is radian. | | rotation | number | Yes | 0 | Rotation angle of the ellipse. The unit is radian. |
| startAngle | number | Yes | 0 | Angle of the start point for drawing the ellipse. The unit is radian.| | startAngle | number | Yes | 0 | Angle of the start point for drawing the ellipse. The unit is radian.|
| endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse. The unit is radian.| | endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse. The unit is radian.|
| counterclockwise | boolean | No | false | Whether to draw the ellipse in the counterclockwise direction. | | counterclockwise | boolean | No | false | Whether to draw the ellipse counterclockwise.<br>**true**: Draw the ellipse counterclockwise.<br>**false**: Draw the ellipse clockwise. |
**Example** **Example**
...@@ -1665,17 +1665,17 @@ struct Fill { ...@@ -1665,17 +1665,17 @@ struct Fill {
.height('100%') .height('100%')
.backgroundColor('#ffff00') .backgroundColor('#ffff00')
.onReady(() =>{ .onReady(() =>{
let region = new Path2D(); let region = new Path2D()
region.moveTo(30, 90); region.moveTo(30, 90)
region.lineTo(110, 20); region.lineTo(110, 20)
region.lineTo(240, 130); region.lineTo(240, 130)
region.lineTo(60, 130); region.lineTo(60, 130)
region.lineTo(190, 20); region.lineTo(190, 20)
region.lineTo(270, 90); region.lineTo(270, 90)
region.closePath(); region.closePath()
// Fill path // Fill path
this.offContext.fillStyle = 'green'; this.offContext.fillStyle = 'green'
this.offContext.fill(region, "evenodd"); this.offContext.fill(region, "evenodd")
var image = this.offContext.transferToImageBitmap() var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image) this.context.transferFromImageBitmap(image)
}) })
...@@ -1767,9 +1767,9 @@ struct Clip { ...@@ -1767,9 +1767,9 @@ struct Clip {
.height('100%') .height('100%')
.backgroundColor('#ffff00') .backgroundColor('#ffff00')
.onReady(() =>{ .onReady(() =>{
let region = new Path2D(); let region = new Path2D()
region.rect(80,10,20,130); region.rect(80,10,20,130)
region.rect(40,50,100,50); region.rect(40,50,100,50)
this.offContext.clip(region,"evenodd") this.offContext.clip(region,"evenodd")
this.offContext.fillStyle = "rgb(255,0,0)" this.offContext.fillStyle = "rgb(255,0,0)"
this.offContext.fillRect(0, 0, 600, 600) this.offContext.fillRect(0, 0, 600, 600)
...@@ -2031,8 +2031,6 @@ Resets the existing transformation matrix and creates a new transformation matri ...@@ -2031,8 +2031,6 @@ Resets the existing transformation matrix and creates a new transformation matri
![en-us_image_0000001193872526](figures/en-us_image_0000001193872526.png) ![en-us_image_0000001193872526](figures/en-us_image_0000001193872526.png)
### translate
### translate ### translate
translate(x: number, y: number): void translate(x: number, y: number): void
...@@ -2218,8 +2216,8 @@ Obtains the **[ImageData](ts-components-canvas-imagedata.md)** object created wi ...@@ -2218,8 +2216,8 @@ Obtains the **[ImageData](ts-components-canvas-imagedata.md)** object created wi
@Entry @Entry
@Component @Component
struct GetImageData { struct GetImageData {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
private img:ImageBitmap = new ImageBitmap("/common/images/1234.png") private img:ImageBitmap = new ImageBitmap("/common/images/1234.png")
...@@ -2230,9 +2228,9 @@ struct GetImageData { ...@@ -2230,9 +2228,9 @@ struct GetImageData {
.height('100%') .height('100%')
.backgroundColor('#ffff00') .backgroundColor('#ffff00')
.onReady(() =>{ .onReady(() =>{
this.offContext.drawImage(this.img,0,0,130,130); this.offContext.drawImage(this.img,0,0,130,130)
var imagedata = this.offContext.getImageData(50,50,130,130); var imagedata = this.offContext.getImageData(50,50,130,130)
this.offContext.putImageData(imagedata,150,150); this.offContext.putImageData(imagedata,150,150)
var image = this.offContext.transferToImageBitmap() var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image) this.context.transferFromImageBitmap(image)
}) })
...@@ -2334,7 +2332,7 @@ struct SetLineDash { ...@@ -2334,7 +2332,7 @@ struct SetLineDash {
.onReady(() =>{ .onReady(() =>{
this.offContext.arc(100, 75, 50, 0, 6.28) this.offContext.arc(100, 75, 50, 0, 6.28)
this.offContext.setLineDash([10,20]) this.offContext.setLineDash([10,20])
this.offContext.stroke(); this.offContext.stroke()
var image = this.offContext.transferToImageBitmap() var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image) this.context.transferFromImageBitmap(image)
}) })
...@@ -2388,7 +2386,7 @@ struct OffscreenCanvasGetLineDash { ...@@ -2388,7 +2386,7 @@ struct OffscreenCanvasGetLineDash {
.onReady(() => { .onReady(() => {
this.offContext.arc(100, 75, 50, 0, 6.28) this.offContext.arc(100, 75, 50, 0, 6.28)
this.offContext.setLineDash([10,20]) this.offContext.setLineDash([10,20])
this.offContext.stroke(); this.offContext.stroke()
let res = this.offContext.getLineDash() let res = this.offContext.getLineDash()
var image = this.offContext.transferToImageBitmap() var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image) this.context.transferFromImageBitmap(image)
...@@ -2441,7 +2439,7 @@ struct ToDataURL { ...@@ -2441,7 +2439,7 @@ struct ToDataURL {
.height('100%') .height('100%')
.backgroundColor('#ffff00') .backgroundColor('#ffff00')
.onReady(() =>{ .onReady(() =>{
var dataURL = this.offContext.toDataURL(); var dataURL = this.offContext.toDataURL()
}) })
} }
.width('100%') .width('100%')
...@@ -2538,11 +2536,11 @@ struct CanvasExample { ...@@ -2538,11 +2536,11 @@ struct CanvasExample {
.height('100%') .height('100%')
.backgroundColor('#ffff00') .backgroundColor('#ffff00')
.onReady(() =>{ .onReady(() =>{
this.offContext.save(); // save the default state this.offContext.save() // save the default state
this.offContext.fillStyle = "green"; this.offContext.fillStyle = "green"
this.offContext.fillRect(20, 20, 100, 100); this.offContext.fillRect(20, 20, 100, 100)
this.offContext.restore(); // restore to the default state this.offContext.restore() // restore to the default state
this.offContext.fillRect(150, 75, 100, 100); this.offContext.fillRect(150, 75, 100, 100)
var image = this.offContext.transferToImageBitmap() var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image) this.context.transferFromImageBitmap(image)
}) })
...@@ -2579,11 +2577,11 @@ struct CanvasExample { ...@@ -2579,11 +2577,11 @@ struct CanvasExample {
.height('100%') .height('100%')
.backgroundColor('#ffff00') .backgroundColor('#ffff00')
.onReady(() =>{ .onReady(() =>{
this.offContext.save(); // save the default state this.offContext.save() // save the default state
this.offContext.fillStyle = "green"; this.offContext.fillStyle = "green"
this.offContext.fillRect(20, 20, 100, 100); this.offContext.fillRect(20, 20, 100, 100)
this.offContext.restore(); // restore to the default state this.offContext.restore() // restore to the default state
this.offContext.fillRect(150, 75, 100, 100); this.offContext.fillRect(150, 75, 100, 100)
var image = this.offContext.transferToImageBitmap() var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image) this.context.transferFromImageBitmap(image)
}) })
......
...@@ -10,29 +10,19 @@ You can draw an image around a component. ...@@ -10,29 +10,19 @@ You can draw an image around a component.
| Name | Type | Description | | Name | Type | Description |
| ---------- | ---------------------------------------- | --------------------------------------- | | ---------- | ---------------------------------------- | --------------------------------------- |
| borderImage | BorderImageOption | Border image or border gradient. | | borderImage | [BorderImageOption](#borderimageoption) | Border image or border gradient. |
## BorderImageOption ## BorderImageOption
| Name | Type | Description | | Name | Type | Description |
| ---------- | ---------------------------------------- | --------------------------------------- | | ---------- | ---------------------------------------- | --------------------------------------- |
| source | string \| [Resource](ts-types.md#resource) \| [linearGradient](ts-universal-attributes-gradient-color.md) | Source or gradient color of the border image. | | source | string \| [Resource](ts-types.md#resource) \| [linearGradient](ts-universal-attributes-gradient-color.md) | Source or gradient color of the border image. |
| slice | [Length](ts-types.md#length)\| EdgeWidths | Slice width of the border image.<br>Default value: **0** | | slice | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Slice width of the border image.<br>Default value: **0** |
| width | [Length](ts-types.md#length)\| EdgeWidths | Width of the border image.<br>Default value: **0** | | width | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Width of the border image.<br>Default value: **0** |
| outset | [Length](ts-types.md#length)\| EdgeWidths | Amount by which the border image is extended beyond the border box.<br>Default value: **0** | | outset | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Amount by which the border image is extended beyond the border box.<br>Default value: **0** |
| RepeatMode | RepeatMode | Repeat mode of the border image.<br>Default value: **RepeatMode.Stretch**| | repeat | [RepeatMode](#repeatmode) | Repeat mode of the border image.<br>Default value: **RepeatMode.Stretch**|
| fill | boolean | Whether to fill the center of the border image.<br>Default value: **false** | | fill | boolean | Whether to fill the center of the border image.<br>Default value: **false** |
## EdgeWidths
At least one parameter must be passed to reference an **EdgeWidth** object.
| Name| Type| Mandatory|Description|
| -------- | -------- |-------- |-------- |
| left | [Length](ts-types.md#length) | No| Distance on the left.|
| right | [Length](ts-types.md#length) | No| Distance on the right.|
| top | [Length](ts-types.md#length) | No| Distance at the top.|
| bottom | [Length](ts-types.md#length) | No| Distance on the bottom.|
## RepeatMode ## RepeatMode
...@@ -51,19 +41,31 @@ At least one parameter must be passed to reference an **EdgeWidth** object. ...@@ -51,19 +41,31 @@ At least one parameter must be passed to reference an **EdgeWidth** object.
@Entry @Entry
@Component @Component
struct Index { struct Index {
@State outSetValue: number = 40
build() { build() {
Row() { Row() {
Column() { Column() {
Text('This is\nborderImage.').textAlign(TextAlign.Center) Text('This is borderImage.').textAlign(TextAlign.Center).fontSize(50)
.borderImage({ .borderImage({
source: "borderOrigin.png", source: $r('app.media.heart'),
slice: {top:"31%", bottom:"31%", left:"31%", right:"31%"}, slice: `${this.outSetValue}%`,
width: {top:"20px", bottom:"20px", left:"20px", right:"20px"}, width: `${this.outSetValue}px`,
outset: {top:"5px", bottom:"5px", left:"5px", right:"5px"}, outset: '5px',
repeat: RepeatMode.Repeat, repeat: RepeatMode.Repeat,
fill: false fill: false
}); })
Slider({
value: this.outSetValue,
min: 0,
max: 100,
style: SliderStyle.OutSet
})
.margin({ top: 30 })
.onChange((value: number, mode: SliderChangeMode) => {
this.outSetValue = value
console.info('value:' + value + 'mode:' + mode.toString())
})
} }
.width('100%') .width('100%')
} }
...@@ -72,7 +74,7 @@ struct Index { ...@@ -72,7 +74,7 @@ struct Index {
} }
``` ```
![en-us_image_borderImage](figures/borderImage.png) ![en-us_image_borderImage](figures/borderImage.gif)
```ts ```ts
...@@ -80,20 +82,21 @@ struct Index { ...@@ -80,20 +82,21 @@ struct Index {
@Entry @Entry
@Component @Component
struct Index { struct Index {
build() { build() {
Row() { Row() {
Column() { Column() {
Text('This is\ngradient color.').textAlign(TextAlign.Center) Text('This is gradient color.').textAlign(TextAlign.Center)
.borderImage({ .borderImage({
source: {angle:90, source: {
angle: 90,
direction: GradientDirection.Left, direction: GradientDirection.Left,
colors: [[0xAEE1E1, 0.0], [0xD3E0DC, 0.3], [0xFCD1D1, 1.0]]}, colors: [[0xAEE1E1, 0.0], [0xD3E0DC, 0.3], [0xFCD1D1, 1.0]]
slice: {top:10, bottom:10, left:10, right:10}, },
width: {top:"10px", bottom:"10px", left: "10px", right:"10px"}, slice: { top: 10, bottom: 10, left: 10, right: 10 },
width: { top: "10px", bottom: "10px", left: "10px", right: "10px" },
repeat: RepeatMode.Stretch, repeat: RepeatMode.Stretch,
fill: false fill: false
}); })
} }
.width('100%') .width('100%')
} }
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
Focus control attributes set whether a component is focusable, how it participates in sequential keyboard navigation, Focus control attributes set whether a component is focusable, how it participates in sequential keyboard navigation,
> **NOTE**<br> > **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. > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
...@@ -11,11 +11,11 @@ Focus control attributes set whether a component is focusable, how it participat ...@@ -11,11 +11,11 @@ Focus control attributes set whether a component is focusable, how it participat
| Name | Type| Description | | Name | Type| Description |
| -------------------- | -------- | ---------------------------------------- | | -------------------- | -------- | ---------------------------------------- |
| focusable | boolean | Whether the current component is focusable.<br>**NOTE**<br>Components that have default interaction logic, such as **\<Button>** and **\<TextInput>**, are focusable by default. Other components, such as **\<Text>** and **\<Image>**, are not focusable by default. | | focusable | boolean | Whether the current component is focusable.<br>**NOTE**<br><br>Components that have default interaction logic, such as **\<Button>** and **\<TextInput>**, are focusable by default. Other components, such as **\<Text>** and **\<Image>**, are not focusable by default. |
| tabIndex<sup>9+<sup> | number | How the current component participates in sequential keyboard navigation.<br>- **tabIndex** >= 0: The component is focusable in sequential keyboard navigation, with its order defined by the value. A component with a larger value is focused after one with a smaller value. If multiple components share the same **tabIndex** value, their focus order follows their position in the component tree.<br>- **tabIndex** < 0 (usually **tabIndex** = -1): The component is focusable, but cannot be reached through sequential keyboard navigation.<br>Default value: **0**| | tabIndex<sup>9+</sup> | number | How the current component participates in sequential keyboard navigation.<br>- **tabIndex** >= 0: The component is focusable in sequential keyboard navigation, with its order defined by the value. A component with a larger value gains focus later than one with a smaller value. If multiple components share the same **tabIndex** value, their focus order follows their position in the component tree.<br>- **tabIndex** < 0 (usually **tabIndex** = -1): The component is focusable, but cannot be reached through sequential keyboard navigation.<br>Default value: **0**|
| defaultFocus<sup>9+<sup> | boolean | Whether to set the current component as the default focus of the page. This attribute takes effect only when the page is new and accessed for the first time.<br>Default value: **false**| | defaultFocus<sup>9+</sup> | boolean | Whether to set the current component as the default focus of the page. This attribute takes effect only when the page is new and accessed for the first time.<br>Default value: **false**|
| groupDefaultFocus<sup>9+<sup> | boolean | Whether to set the current component as the default focus of the parent container. This attribute takes effect only when the container is new and has focus for the first time.<br>Default value: **false**<br>**NOTE**<br>This attribute must be used together with **tabIndex**. When **tabIndex** is set for a container and **groupDefaultFocus** is set for a component in the container, the focus is automatically shifted to that component when the container obtains the focus for the first time.<br>| | groupDefaultFocus<sup>9+</sup> | boolean | Whether to set the current component as the default focus of the parent container. This attribute takes effect only when the container is new and has focus for the first time.<br>Default value: **false**<br>**NOTE**<br>This attribute must be used together with **tabIndex**. When **tabIndex** is set for a container and **groupDefaultFocus** is set for a component in the container, the focus is automatically shifted to that component when the container obtains the focus for the first time.<br>|
| focusOnTouch<sup>9+<sup> | boolean | Whether the current component is focusable on touch.<br>Default value: **false**<br>**NOTE**<br>The component can obtain focus only when it is touchable or clickable.| | focusOnTouch<sup>9+</sup> | boolean | Whether the current component is focusable on touch.<br>Default value: **false**<br>**NOTE**<br>The component can obtain focus only when it is touchable or clickable.|
## focusControl<sup>9+</sup> ## focusControl<sup>9+</sup>
...@@ -37,7 +37,8 @@ Requests the focus to move to the specified component. This API can be used in g ...@@ -37,7 +37,8 @@ Requests the focus to move to the specified component. This API can be used in g
| ------- | ---- | | ------- | ---- |
| boolean | Returns whether the focus is successfully moved to the target component. Returns **true** if the specified component exists and the focus is successfully moved to the target component; returns **false** otherwise.| | boolean | Returns whether the focus is successfully moved to the target component. Returns **true** if the specified component exists and the focus is successfully moved to the target component; returns **false** otherwise.|
> **NOTE**<br> > **NOTE**
>
> The following components support focus control: **\<Button>**, **\<Text>**, **\<Image>**, **\<List>**, and **\<Grid>**. Currently, the running effect of the focus event can be displayed only on a real device. > The following components support focus control: **\<Button>**, **\<Text>**, **\<Image>**, **\<List>**, and **\<Grid>**. Currently, the running effect of the focus event can be displayed only on a real device.
## Example ## Example
...@@ -86,7 +87,7 @@ struct FocusableExample { ...@@ -86,7 +87,7 @@ struct FocusableExample {
.fontColor(Color.White) .fontColor(Color.White)
} }
}.borderWidth(2).borderColor(Color.Red).borderStyle(BorderStyle.Dashed) }.borderWidth(2).borderColor(Color.Red).borderStyle(BorderStyle.Dashed)
.tabIndex(1) // This column is the initial component to have focus in sequential keyboard navigation. .tabIndex(1) // The column is the initial component to have focus in sequential keyboard navigation.
Column({ space: 5 }) { Column({ space: 5 }) {
Button('Group2') Button('Group2')
.width(165) .width(165)
...@@ -114,14 +115,14 @@ struct FocusableExample { ...@@ -114,14 +115,14 @@ struct FocusableExample {
.fontColor(Color.White) .fontColor(Color.White)
} }
}.borderWidth(2).borderColor(Color.Green).borderStyle(BorderStyle.Dashed) }.borderWidth(2).borderColor(Color.Green).borderStyle(BorderStyle.Dashed)
.tabIndex(2) // This column is the second component to have focus in sequential keyboard navigation. .tabIndex(2) // The column is the second component to have focus in sequential keyboard navigation.
} }
Column({ space: 5 }) { Column({ space: 5 }) {
TextInput({placeholder: 'input', text: this.inputValue}) TextInput({placeholder: 'input', text: this.inputValue})
.onChange((value: string) => { .onChange((value: string) => {
this.inputValue = value this.inputValue = value
}) })
.defaultFocus(true) // This <TextInput> component is the initial default focus of the page. .defaultFocus(true) // The <TextInput> component is the initial default focus of the page.
Button('Group3') Button('Group3')
.width(165) .width(165)
.height(40) .height(40)
...@@ -165,7 +166,7 @@ struct FocusableExample { ...@@ -165,7 +166,7 @@ struct FocusableExample {
.fontColor(Color.White) .fontColor(Color.White)
} }
}.borderWidth(2).borderColor(Color.Orange).borderStyle(BorderStyle.Dashed) }.borderWidth(2).borderColor(Color.Orange).borderStyle(BorderStyle.Dashed)
.tabIndex(3) // This column is the third component to have focus in sequential keyboard navigation. .tabIndex(3) // The column is the third component to have focus in sequential keyboard navigation.
}.alignItems(VerticalAlign.Top) }.alignItems(VerticalAlign.Top)
} }
} }
...@@ -200,7 +201,7 @@ Sample code for **focusControl.requestFocus**: ...@@ -200,7 +201,7 @@ Sample code for **focusControl.requestFocus**:
Use the **focusContrl.requestFocus** API to enable a specified component to obtain the focus. Use the **focusContrl.requestFocus** API to enable a specified component to obtain the focus.
```ts ```ts
// requestFocus.ets // requestFocus.ets
import prompt from '@system.prompt'; import prompt from '@ohos.prompt'
@Entry @Entry
@Component @Component
...@@ -266,14 +267,15 @@ struct RequestFocusExample { ...@@ -266,14 +267,15 @@ struct RequestFocusExample {
Diagrams: Diagrams:
Press the Tab button to activate the focus state. Press the Tab button to activate the focus state.
Request focus for a component that does not exist.
Below show how the UI behaves when you request focus for a component that does not exist.
![requestFocus1](figures/requestFocus1.png) ![requestFocus1](figures/requestFocus1.png)
Request focus for a component that is not focusable. Below show how the UI behaves when you request focus for a component that is not focusable.
![requestFocus2](figures/requestFocus2.png) ![requestFocus2](figures/requestFocus2.png)
Request focus for a focusable component. Below show how the UI behaves when you request focus for a focusable component.
![requestFocus3](figures/requestFocus3.png) ![requestFocus3](figures/requestFocus3.png)
# Image Effects # Image Effects
Image effects include background blur, content blur, grayscale, and much more. Image effects include blur, shadow, and much more.
> **NOTE** > **NOTE**
>
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Attributes ## Attributes
| Name | Type | Default Value| Description | | Name | Type | Default Value| Description |
| ----------------------------- | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | | ----------------------------- | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ |
| blur | number | - | Adds the content blur effect to the current component. The input parameter is the blur radius. The larger the radius is, the more blurred the content is. If the value is **0**, the content is not blurred. | | blur | number | - | Applies the content blur effect to the current component. The input parameter is the blur radius. The larger the radius is, the more blurred the content is. If the value is **0**, the content is not blurred.|
| backdropBlur | number | - | Adds the background blur effect to the current component. The input parameter is the blur radius. The larger the radius is, the more blurred the background is. If the value is **0**, the background is not blurred. | | backdropBlur | number | - | Applies the background blur effect to the current component. The input parameter is the blur radius. The larger the radius is, the more blurred the background is. If the value is **0**, the background is not blurred.|
| shadow | {<br>radius: number \| [Resource](ts-types.md#resource),<br>color?: Color \| string \| Resource,<br>offsetX?: number \| Resource,<br>offsetY?: number \| Resource<br>} | - | Adds the shadow effect to the current component. The input parameters are the fuzzy radius (mandatory), shadow color (optional; gray by default), x-axis offset (optional; 0 by default), and y-axis offset (optional; 0 by default). The offset unit is px.| | shadow | {<br>radius: number \| [Resource](ts-types.md#resource),<br>color?: [Color](ts-appendix-enums.md#color) \| string \| [Resource](ts-types.md#resource),<br>offsetX?: number \| [Resource](ts-types.md#resource),<br>offsetY?: number \| [Resource](ts-types.md#resource)<br>} | - | Applies the shadow effect to the current component. The input parameters are the fuzzy radius (mandatory), shadow color (optional; gray by default), x-axis offset (optional; 0 by default), and y-axis offset (optional; 0 by default). The offset unit is px.|
| grayscale | number | 0.0 | Converts the input image to grayscale. The value indicates the grayscale conversion ratio. If the input value is **1.0**, the image is converted into a grayscale image. If the input value is **0.0**, the image does not change. If the input value is between **0.0** and **1.0**, the effect changes in linear mode. The unit is percentage.| | grayscale | number | 0.0 | Converts the input image to grayscale. The value indicates the grayscale conversion ratio. If the input value is **1.0**, the image is converted into a grayscale image. If the input value is **0.0**, the image does not change. If the input value is between **0.0** and **1.0**, the effect changes in linear mode. The unit is percentage.|
| brightness | number | 1.0 | Adds a brightness to the current component. The input parameter is a brightness ratio. The value **1** indicates no effects. The value **0** indicates the complete darkness. If the value is less than **1**, the brightness decreases. If the value is greater than **1**, the brightness increases. A larger value indicates a higher brightness.| | brightness | number | 1.0 | Applies a brightness to the current component. The input parameter is a brightness ratio. The value **1** indicates no effects. The value **0** indicates the complete darkness. If the value is less than **1**, the brightness decreases. If the value is greater than **1**, the brightness increases. A larger value indicates a higher brightness.|
| saturate | number | 1.0 | Adds the saturation effect to the current component. The saturation is the ratio of the chromatic component to the achromatic component (gray) in a color. When the input value is **1**, the source image is displayed. When the input value is greater than **1**, a higher percentage of the chromatic component indicates a higher saturation. When the input value is less than **1**, a higher percentage of the achromatic component indicates a lower saturation. The unit is percentage.| | saturate | number | 1.0 | Applies the saturation effect to the current component. The saturation is the ratio of the chromatic component to the achromatic component (gray) in a color. When the input value is **1**, the source image is displayed. When the input value is greater than **1**, a higher percentage of the chromatic component indicates a higher saturation. When the input value is less than **1**, a higher percentage of the achromatic component indicates a lower saturation. The unit is percentage.|
| contrast | number | 1.0 | Adds the contrast effect to the current component. The input parameter is a contrast value. If the value is **1**, the source image is displayed. If the value is greater than **1**, a larger value indicates a higher contrast and a clearer image. If the value is less than **1**, a smaller value indicates a lower contrast is. If the value is **0**, the image becomes all gray. The unit is percentage.| | contrast | number | 1.0 | Applies the contrast effect to the current component. The input parameter is a contrast value. If the value is **1**, the source image is displayed. If the value is greater than **1**, a larger value indicates a higher contrast and a clearer image. If the value is less than **1**, a smaller value indicates a lower contrast is. If the value is **0**, the image becomes all gray. The unit is percentage.|
| invert | number | 0 | Inverts the input image. The input parameter is an image inversion ratio. The value **1** indicates complete inversion. The value **0** indicates that the image does not change. The unit is percentage.| | invert | number | 0 | Inverts the input image. The input parameter is an image inversion ratio. The value **1** indicates complete inversion. The value **0** indicates that the image does not change. The unit is percentage.|
| colorBlend <sup>8+</sup> | Color \| string \| [Resource](ts-types.md#resource) | - | Adds the color blend effect to the current component. The input parameter is the blended color. |
| sepia | number | 0 | Converts the image color to sepia. The input parameter is an image inversion ratio. The value **1** indicates the image is completely sepia. The value **0** indicates that the image does not change. The unit is percentage.| | sepia | number | 0 | Converts the image color to sepia. The input parameter is an image inversion ratio. The value **1** indicates the image is completely sepia. The value **0** indicates that the image does not change. The unit is percentage.|
| hueRotate | number\|string | '0deg' | Adds the hue rotation effect to the current component. The input parameter is a rotation angle. | | hueRotate | number \| string | '0deg' | Applies the hue rotation effect to the current component. The input parameter is a rotation angle. |
| colorBlend <sup>8+</sup> | [Color](ts-appendix-enums.md#color) \| string \| [Resource](ts-types.md#resource) | - | Applies the color blend effect to the current component. The input parameter is the blended color. |
## Example ## Example
You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer. ### Example 1
Use **blur** to add the content blur effect and **backdropBlur** to add the background blur effect.
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct ImageEffectsExample { struct BlurEffectsExample {
build() { build() {
Column({space: 10}) { Column({ space: 10 }) {
// Blur the font. // Blur the font.
Text('font blur').fontSize(15).fontColor(0xCCCCCC).width('90%') Text('font blur').fontSize(15).fontColor(0xCCCCCC).width('90%')
Text('text').blur(3).width('90%').height(40) Flex({ alignItems: ItemAlign.Center }) {
.fontSize(16).backgroundColor(0xF9CF93).padding({ left: 5 }) Text('original text').margin(10)
Text('blur text')
.blur(1).margin(10)
Text('blur text')
.blur(2).margin(10)
Text('blur text')
.blur(3).margin(10)
}.width('90%').height(40)
.backgroundColor(0xF9CF93)
// Blur the background. // Blur the background.
Text('backdropBlur').fontSize(15).fontColor(0xCCCCCC).width('90%') Text('backdropBlur').fontSize(15).fontColor(0xCCCCCC).width('90%')
Text().width('90%').height(40).fontSize(16).backdropBlur(3) Text()
.backgroundImage('/comment/bg.jpg') .width('90%')
.height(40)
.fontSize(16)
.backdropBlur(3)
.backgroundImage('/pages/attrs/image/image.jpg')
.backgroundImageSize({ width: 1200, height: 160 }) .backgroundImageSize({ width: 1200, height: 160 })
}.width('100%').margin({ top: 5 })
}
}
```
![textblur](figures/textblur.png)
### Example 2
Apply different image effects.
```ts
// xxx.ets
@Entry
@Component
struct ImageEffectsExample {
build() {
Column({ space: 10 }) {
// Apply the shadow effect.
Text('shadow').fontSize(15).fontColor(0xCCCCCC).width('90%') Text('shadow').fontSize(15).fontColor(0xCCCCCC).width('90%')
Image($r('app.media.bg')).width('90%').height(40) Image($r('app.media.image'))
.shadow({ radius: 10, color: Color.Gray, offsetX: 5, offsetY: 5 }) .width('90%')
.height(40)
.shadow({ radius: 10, color: Color.Green, offsetX: 20, offsetY: 30 })
// Apply the grayscale effect. The grayscale value ranges from 0 to 1. The closer the grayscale value is to 1, the more obvious the grayscale effect is.
Text('grayscale').fontSize(15).fontColor(0xCCCCCC).width('90%') Text('grayscale').fontSize(15).fontColor(0xCCCCCC).width('90%')
Image($r('app.media.bg')).width('90%').height(40).grayscale(0.6) Image($r('app.media.image')).width('90%').height(40).grayscale(0.3)
Image($r('app.media.image')).width('90%').height(40).grayscale(0.8)
// Apply the brightness effect. The value 1 indicates no effects. If the value is less than 1, the brightness decreases. If the value is greater than 1, the brightness increases.
Text('brightness').fontSize(15).fontColor(0xCCCCCC).width('90%') Text('brightness').fontSize(15).fontColor(0xCCCCCC).width('90%')
Image($r('app.media.bg')).width('90%').height(40).brightness(2.0) Image($r('app.media.image')).width('90%').height(40).brightness(1.2)
// Apply the saturation effect. If the value is 1, the source image is displayed.
Text('saturate').fontSize(15).fontColor(0xCCCCCC).width('90%') Text('saturate').fontSize(15).fontColor(0xCCCCCC).width('90%')
Image($r('app.media.bg')).width('90%').height(40).saturate(2.0) Image($r('app.media.image')).width('90%').height(40).saturate(2.0)
Image($r('app.media.image')).width('90%').height(40).saturate(0.7)
// Apply the contrast effect. If the value is 1, the source image is displayed. If the value is greater than 1, a larger value indicates a higher contrast and a clearer image. If the value is less than 1, a smaller value indicates a lower contrast is.
Text('contrast').fontSize(15).fontColor(0xCCCCCC).width('90%') Text('contrast').fontSize(15).fontColor(0xCCCCCC).width('90%')
Image($r('app.media.bg')).width('90%').height(40).contrast(2.0) Image($r('app.media.image')).width('90%').height(40).contrast(2.0)
Image($r('app.media.image')).width('90%').height(40).contrast(0.8)
// Invert the image.
Text('invert').fontSize(15).fontColor(0xCCCCCC).width('90%') Text('invert').fontSize(15).fontColor(0xCCCCCC).width('90%')
Image($r('app.media.bg')).width('90%').height(40).invert(1) Image($r('app.media.image')).width('90%').height(40).invert(0.2)
Image($r('app.media.image')).width('90%').height(40).invert(0.8)
// Apply the color blend effect.
Text('colorBlend').fontSize(15).fontColor(0xCCCCCC).width('90%')
Image($r('app.media.image')).width('90%').height(40).colorBlend(Color.Green)
Image($r('app.media.image')).width('90%').height(40).colorBlend(Color.Blue)
// Convert the image color to sepia.
Text('sepia').fontSize(15).fontColor(0xCCCCCC).width('90%')
Image($r('app.media.image')).width('90%').height(40).sepia(0.8)
// Apply the hue rotation effect.
Text('hueRotate').fontSize(15).fontColor(0xCCCCCC).width('90%') Text('hueRotate').fontSize(15).fontColor(0xCCCCCC).width('90%')
Image($r('app.media.bg')).width('90%').height(40).hueRotate(90) Image($r('app.media.image')).width('90%').height(40).hueRotate(90)
}.width('100%').margin({ top: 5 }) }.width('100%').margin({ top: 5 })
} }
} }
``` ```
![](figures/image-effect.png) ![imageeffect](figures/imageeffect.png)
...@@ -20,11 +20,11 @@ You can bind a popup to a component, specifying its content, interaction logic, ...@@ -20,11 +20,11 @@ You can bind a popup to a component, specifying its content, interaction logic,
| -------------------------| ------------------------------------------------| -----| ----------------------------------------- | | -------------------------| ------------------------------------------------| -----| ----------------------------------------- |
| message | string | Yes | Content of the popup message. | | message | string | Yes | Content of the popup message. |
| placementOnTop | boolean | No | Whether to display the popup above the component. The default value is **false**. | | placementOnTop | boolean | No | Whether to display the popup above the component. The default value is **false**. |
| arrowOffset<sup>9+</sup> | [Length](ts-types.md#length) | No | Offset of the popup arrow in the popup window. When residing above or below the popup, the arrow is offset to the left by default. When residing on the left or right side of the popup, the arrow is offset to the top by default. |
| showInSubWindow<sup>9+</sup> | boolean | No | Whether to show the popup in the subwindow. The default value is **false**.|
| primaryButton | {<br>value: string,<br>action: () =&gt; void<br>} | No | Primary button.<br>**value**: text of the primary button in the popup.<br>**action**: callback for clicking the primary button.| | primaryButton | {<br>value: string,<br>action: () =&gt; void<br>} | No | Primary button.<br>**value**: text of the primary button in the popup.<br>**action**: callback for clicking the primary button.|
| secondaryButton | {<br>value: string,<br>action: () =&gt; void<br>} | No | Secondary button.<br>**value**: text of the secondary button in the popup.<br>**action**: callback for clicking the secondary button.| | secondaryButton | {<br>value: string,<br>action: () =&gt; void<br>} | No | Secondary button.<br>**value**: text of the secondary button in the popup.<br>**action**: callback for clicking the secondary button.|
| onStateChange | (event: { isVisible: boolean }) =&gt; void | No | Callback for the popup status change event. The parameter **isVisible** indicates whether the popup is visible. | | onStateChange | (event: { isVisible: boolean }) =&gt; void | No | Callback for the popup status change event. The parameter **isVisible** indicates whether the popup is visible. |
| arrowOffset<sup>9+</sup> | [Length](ts-types.md#length) | No | Offset of the popup arrow in the popup window. When residing above or below the popup, the arrow is offset to the left by default. When residing on the left or right side of the popup, the arrow is offset to the top by default.|
| showInSubWindow<sup>9+</sup> | boolean | No| Whether to show the popup in the subwindow. The default value is **false**.|
## CustomPopupOptions<sup>8+</sup> ## CustomPopupOptions<sup>8+</sup>
...@@ -32,13 +32,13 @@ You can bind a popup to a component, specifying its content, interaction logic, ...@@ -32,13 +32,13 @@ You can bind a popup to a component, specifying its content, interaction logic,
| -------------------------| ------------------------- | ---- | ---------------------------------------------------- | | -------------------------| ------------------------- | ---- | ---------------------------------------------------- |
| builder | [CustomBuilder](ts-types.md#custombuilder8) | Yes | Popup builder. | | builder | [CustomBuilder](ts-types.md#custombuilder8) | Yes | Popup builder. |
| placement | [Placement](ts-appendix-enums.md#placement8) | No | Preferred position of the popup. If the set position is insufficient for holding the popup, it will be automatically adjusted.<br>Default value: **Placement.Bottom** | | placement | [Placement](ts-appendix-enums.md#placement8) | No | Preferred position of the popup. If the set position is insufficient for holding the popup, it will be automatically adjusted.<br>Default value: **Placement.Bottom** |
| arrowOffset<sup>9+</sup> | [Length](ts-types.md#length) | No | Offset of the popup arrow in the popup window. When residing above or below the popup, the arrow is offset to the left by default. When residing on the left or right side of the popup, the arrow is offset to the top by default. |
| showInSubWindow<sup>9+</sup> | boolean | No | Whether to show the popup in the subwindow. The default value is **false**.|
| maskColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the popup mask. | | maskColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the popup mask. |
| popupColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the popup. | | popupColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the popup. |
| enableArrow | boolean | No | Whether to display an arrow.<br>Since API version 9, if the location set for the popup arrow is not large enough, the arrow will not be displayed. For example, if **placement** is set to **Left** and the popup height is less than the arrow width (32 vp), the arrow will not be displayed.<br>Default value: **true**| | enableArrow | boolean | No | Whether to display an arrow.<br>Since API version 9, if the location set for the popup arrow is not large enough, the arrow will not be displayed. For example, if **placement** is set to **Left** and the popup height is less than the arrow width (32 vp), the arrow will not be displayed.<br>Default value: **true**|
| autoCancel | boolean | No | Whether to automatically close the popup when an operation is performed on the page.<br>Default value: **true** | | autoCancel | boolean | No | Whether to automatically close the popup when an operation is performed on the page.<br>Default value: **true** |
| onStateChange | (event: { isVisible: boolean }) =&gt; void | No | Callback for the popup status change event. The parameter **isVisible** indicates whether the popup is visible.| | onStateChange | (event: { isVisible: boolean }) =&gt; void | No | Callback for the popup status change event. The parameter **isVisible** indicates whether the popup is visible.|
| arrowOffset<sup>9+</sup> | [Length](ts-types.md#length) | No| Offset of the popup arrow in the popup window. When residing above or below the popup, the arrow is offset to the left by default. When residing on the left or right side of the popup, the arrow is offset to the top by default.|
| showInSubWindow<sup>9+</sup> | boolean | No| Whether to show the popup in the subwindow. The default value is **false**.|
## Example ## Example
...@@ -80,7 +80,7 @@ struct PopupExample { ...@@ -80,7 +80,7 @@ struct PopupExample {
secondaryButton: { secondaryButton: {
value: 'cancel', value: 'cancel',
action: () => { action: () => {
this.handlePopup = !this.handlePopup; this.handlePopup = !this.handlePopup
console.info('cancel Button click') console.info('cancel Button click')
} }
}, },
......
...@@ -10,35 +10,35 @@ A drag event is triggered when a component is dragged. ...@@ -10,35 +10,35 @@ A drag event is triggered when a component is dragged.
| Name | Bubbling Supported| Description | | Name | Bubbling Supported| Description |
| ---------------------------------------- | ---- | ---------------------------------------- | | ---------------------------------------- | ---- | ---------------------------------------- |
| onDragStart(event: (event?: DragEvent, extraParams?: string) =&gt; [CustomBuilder](ts-types.md#custombuilder8) \| DragItemInfo) | No | Triggered when the component bound to the event is dragged for the first time.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see extraParam.<br>Return value: object being dragged, which is used for prompts displayed when the object is dragged.<br>A drag event can be triggered by a 150 ms long press. If the duration of a long-press gesture is set to less than or equal to 150 ms, the callback for the long-press gesture takes precedence. Otherwise, the callback for the drag event takes precedence.| | onDragStart(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; [CustomBuilder](ts-types.md#custombuilder8) \| [DragItemInfo](#dragiteminfo) | No | Triggered when the component bound to the event is dragged for the first time.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.<br>Return value: object being dragged, which is used for prompts displayed when the object is dragged.<br>A drag event can be triggered by a 150 ms long press. If the duration of a long-press gesture is set to less than or equal to 150 ms, the callback for the long-press gesture takes precedence. Otherwise, the callback for the drag event takes precedence.|
| onDragEnter(event: (event?: DragEvent, extraParams?: string) =&gt; void) | No | Triggered when the dragged item enters a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see extraParam.<br>This event is valid only when the **onDrop** event is listened to.| | onDragEnter(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; void) | No | Triggered when the dragged item enters a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.<br>This event is valid only when the **onDrop** event is listened to.|
| onDragMove(event: (event?: DragEvent, extraParams?: string) =&gt; void) | No | Triggered when the dragged item moves in a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see extraParam.<br>This event is valid only when the **onDrop** event is listened to.| | onDragMove(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; void) | No | Triggered when the dragged item moves in a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.<br>This event is valid only when the **onDrop** event is listened to.|
| onDragLeave(event: (event?: DragEvent, extraParams?: string) =&gt; void) | No | Triggered when the dragged item leaves a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see extraParam.<br>This event is valid only when the **onDrop** event is listened to.| | onDragLeave(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; void) | No | Triggered when the dragged item leaves a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.<br>This event is valid only when the **onDrop** event is listened to.|
| onDrop(event: (event?: DragEvent, extraParams?: string) =&gt; void) | No | Triggered when the dragged item is dropped on a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see extraParam.| | onDrop(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; void) | No | Triggered when the dragged item is dropped on a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.|
## DragItemInfo ## DragItemInfo
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | --------------------------------- | | --------- | ---------------------------------------- | ---- | --------------------------------- |
| pixelMap | [PixelMap](../apis/js-apis-image.md#pixelmap7) | No | Image to be displayed during dragging. | | pixelMap | [PixelMap](../apis/js-apis-image.md#pixelmap7) | No | Image to be displayed during dragging. |
| builder | [CustomBuilder](ts-types.md#custombuilder8) | No | Custom building for drawing. If **pixelMap** is set, this attribute is ignored.| | builder | [CustomBuilder](ts-types.md#custombuilder8) | No | Custom component to display during dragging. If **pixelMap** is set, this attribute is ignored.|
| extraInfo | string | No | Extra information of the dragged item. | | extraInfo | string | No | Extra information of the dragged item. |
## extraParam ## extraParams
Provides additional information required for dragging an item. Provides additional information required for dragging an item.
**extraParam** is a string converted from a JSON object. You can obtain the following attributes using the JSON object converted from **Json.parse**. **extraParams** is a string converted from a JSON object. You can obtain the following attributes using the JSON object converted from **Json.parse**.
| Name | Type | Description | | Name | Type | Description |
| ------------- | ------ | ---------------------------------------- | | ------------- | ------ | ---------------------------------------- |
| selectedIndex | number | Index of the dragged item in the parent container. The value of **selectedindex** starts from **0**.<br>This attribute is valid only in the **ListItem** component.| | selectedIndex | number | Index of the dragged item in the parent container. The value of **selectedindex** starts from **0**.<br>This attribute is valid only in the drag event of the **\<ListItem>** component.|
| insertIndex | number | Index of the element into which the dragged item is dropped in the **List** component. The value of **insertIndex** starts from **0**.<br>This attribute is valid only in the drag event of the **List** component.| | insertIndex | number | Index of the element into which the dragged item is dropped in the **List** component. The value of **insertIndex** starts from **0**.<br>This attribute is valid only in the drag event of the **\<List>** component.|
## DragEvent ## DragEvent
| Name | Return Value Type | Description | | Name | Type | Description |
| ------ | ------ | ---------------- | | ------ | ------ | ---------------- |
| getX() | number | X-coordinate of the item that is being dragged, in vp.| | getX() | number | X-coordinate of the item that is being dragged, in vp.|
| getY() | number | Y-coordinate of the item that is being dragged, in vp.| | getY() | number | Y-coordinate of the item that is being dragged, in vp.|
...@@ -53,98 +53,114 @@ struct DragExample { ...@@ -53,98 +53,114 @@ struct DragExample {
@State numbers: string[] = ['one', 'two', 'three', 'four', 'five', 'six'] @State numbers: string[] = ['one', 'two', 'three', 'four', 'five', 'six']
@State text: string = '' @State text: string = ''
@State bool: boolean = false @State bool: boolean = false
@State bool1: boolean = false
@State appleVisible: Visibility = Visibility.Visible @State appleVisible: Visibility = Visibility.Visible
@State orangeVisible: Visibility = Visibility.Visible @State orangeVisible: Visibility = Visibility.Visible
@State bananaVisible: Visibility = Visibility.Visible @State bananaVisible: Visibility = Visibility.Visible
@State select: number = 0
// Customize the content displayed during dragging.
@Builder pixelMapBuilder() { @Builder pixelMapBuilder() {
Column() { Column() {
Text(this.text) Text(this.text)
.width('50%').height(60).fontSize(16).borderRadius(10) .width('50%')
.textAlign(TextAlign.Center).backgroundColor(Color.Yellow) .height(60)
.fontSize(16)
.borderRadius(10)
.textAlign(TextAlign.Center)
.backgroundColor(Color.Yellow)
} }
} }
build() { build() {
Column() { Column() {
Text('There are three Text elements here') Text('There are three Text elements here')
.fontSize(12).fontColor(0xCCCCCC).width('90%') .fontSize(12)
.textAlign(TextAlign.Start).margin(5) .fontColor(0xCCCCCC)
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceAround }) { .width('90%')
Text('apple').width('25%').height(35).fontSize(16) .textAlign(TextAlign.Start)
.textAlign(TextAlign.Center).backgroundColor(0xAFEEEE) .margin(5)
Row({ space: 15 }) {
Text('apple')
.width('25%')
.height(35)
.fontSize(16)
.textAlign(TextAlign.Center)
.backgroundColor(0xAFEEEE)
.visibility(this.appleVisible) .visibility(this.appleVisible)
.onDragStart(() => { .onDragStart(() => {
this.bool = true this.bool = true
this.text = 'apple' this.text = 'apple'
this.appleVisible = Visibility.Hidden this.appleVisible = Visibility.None
return this.pixelMapBuilder return this.pixelMapBuilder
}) })
Text('orange').width('25%').height(35).fontSize(16) Text('orange')
.textAlign(TextAlign.Center).backgroundColor(0xAFEEEE) .width('25%')
.height(35)
.fontSize(16)
.textAlign(TextAlign.Center)
.backgroundColor(0xAFEEEE)
.visibility(this.orangeVisible) .visibility(this.orangeVisible)
.onDragStart(() => { .onDragStart(() => {
this.bool = true this.bool = true
this.text = 'orange' this.text = 'orange'
this.orangeVisible = Visibility.Hidden this.orangeVisible = Visibility.None
return this.pixelMapBuilder return this.pixelMapBuilder
}) })
Text('banana').width('25%').height(35).fontSize(16) Text('banana')
.textAlign(TextAlign.Center).backgroundColor(0xAFEEEE) .width('25%')
.height(35)
.fontSize(16)
.textAlign(TextAlign.Center)
.backgroundColor(0xAFEEEE)
.visibility(this.bananaVisible) .visibility(this.bananaVisible)
.onDragStart((event: DragEvent, extraParams: string) => { .onDragStart((event: DragEvent, extraParams: string) => {
console.log('Text onDragStarts, ' + extraParams) console.log('Text onDragStart, ' + extraParams + 'X:' + event.getX() + 'Y:' + event.getY())
this.bool = true this.bool = true
this.text = 'banana' this.text = 'banana'
this.bananaVisible = Visibility.Hidden this.bananaVisible = Visibility.None
return this.pixelMapBuilder return this.pixelMapBuilder
}) })
}.border({ width: 1 }).width('90%').padding({ top: 10, bottom: 10 }).margin(10) }.padding({ top: 10, bottom: 10 }).margin(10)
Text('This is a List element').fontSize(12) Text('This is a List element')
.fontColor(0xCCCCCC).width('90%') .fontSize(12)
.textAlign(TextAlign.Start).margin(15) .fontColor(0xCCCCCC)
List({ space: 20, initialIndex: 0 }) { .width('90%')
.textAlign(TextAlign.Start)
.margin(15)
List({ space: 20 }) {
ForEach(this.numbers, (item) => { ForEach(this.numbers, (item) => {
ListItem() { ListItem() {
Text('' + item) Text(item)
.width('100%').height(80).fontSize(16).borderRadius(10) .width('100%')
.textAlign(TextAlign.Center).backgroundColor(0xAFEEEE) .height(80)
.fontSize(16)
.borderRadius(10)
.textAlign(TextAlign.Center)
.backgroundColor(0xAFEEEE)
} }
.onDragStart((event: DragEvent, extraParams: string) => {
console.log('ListItem onDragStarts, ' + extraParams)
var jsonString = JSON.parse(extraParams)
this.bool1 = true
this.text = this.numbers[jsonString.selectedIndex]
this.select = jsonString.selectedIndex
return this.pixelMapBuilder
})
}, item => item) }, item => item)
} }
.editMode(true) .editMode(true)
.height('50%').width('90%').border({ width: 1 }) .height('50%')
.width('90%')
.border({ width: 1 })
.padding(15)
.divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) .divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 })
.onDragEnter((event: DragEvent, extraParams: string) => { .onDragEnter((event: DragEvent, extraParams: string) => {
console.log('List onDragEnter, ' + extraParams) console.log('List onDragEnter, ' + extraParams + 'X:' + event.getX() + 'Y:' + event.getY())
}) })
.onDragMove((event: DragEvent, extraParams: string) => { .onDragMove((event: DragEvent, extraParams: string) => {
console.log('List onDragMove, ' + extraParams) console.log('List onDragMove, ' + extraParams + 'X:' + event.getX() + 'Y:' + event.getY())
}) })
.onDragLeave((event: DragEvent, extraParams: string) => { .onDragLeave((event: DragEvent, extraParams: string) => {
console.log('List onDragLeave, ' + extraParams) console.log('List onDragLeave, ' + extraParams + 'X:' + event.getX() + 'Y:' + event.getY())
}) })
.onDrop((event: DragEvent, extraParams: string) => { .onDrop((event: DragEvent, extraParams: string) => {
var jsonString = JSON.parse(extraParams) var jsonString = JSON.parse(extraParams);
if (this.bool) { if (this.bool) {
// Insert an element using the splice method.
this.numbers.splice(jsonString.insertIndex, 0, this.text) this.numbers.splice(jsonString.insertIndex, 0, this.text)
this.bool = false this.bool = false
} else if (this.bool1) {
this.numbers.splice(jsonString.selectedIndex, 1)
this.numbers.splice(jsonString.insertIndex, 0, this.text)
this.bool = false
this.bool1 = false
} }
}) })
}.width('100%').height('100%').padding({ top: 20 }).margin({ top: 20 }) }.width('100%').height('100%').padding({ top: 20 }).margin({ top: 20 })
...@@ -152,4 +168,4 @@ struct DragExample { ...@@ -152,4 +168,4 @@ struct DragExample {
} }
``` ```
![en-us_image_0000001212218450](figures/en-us_image_0000001212218450.gif) ![en-us_image_0000001252667389](figures/en-us_image_0000001252667389.gif)
# Key Event # Key Event
A key event is triggered when a component interacts with a keyboard, remote control, or any other input device with keys. A key event is triggered when a focusable component, such as **\<Button>**, interacts with a keyboard, remote control, or any other input device with keys. To use a key event for components that are not focusable by default, such as **\<Text>** and **\<Image>**, first set their **focusable** attribute to **true**.
> **NOTE** > **NOTE**
> >
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Events ## Events
| Name | Bubbling Supported| Description | | Name | Bubbling Supported| Description |
...@@ -23,7 +24,7 @@ A key event is triggered when a component interacts with a keyboard, remote cont ...@@ -23,7 +24,7 @@ A key event is triggered when a component interacts with a keyboard, remote cont
| keyText | string | Key value. | | keyText | string | Key value. |
| keySource | [KeySource](ts-appendix-enums.md#keysource) | Type of the input device that triggers the key event. | | keySource | [KeySource](ts-appendix-enums.md#keysource) | Type of the input device that triggers the key event. |
| deviceId | number | ID of the input device that triggers the key event. | | deviceId | number | ID of the input device that triggers the key event. |
| metaKey | number | State of the metakey when the key is pressed. The value **1** means the pressed state, and **0** means the unpressed state.| | metaKey | number | State of the metakey (that is, the **WIN** key on the Windows keyboard or the **Command** key on the Mac keyboard) when the key is pressed. The value **1** indicates the pressed state, and **0** indicates the unpressed state.|
| timestamp | number | Timestamp when the key is pressed. | | timestamp | number | Timestamp when the key is pressed. |
| stopPropagation | () => void | Stops the event from bubbling upwards or downwards. | | stopPropagation | () => void | Stops the event from bubbling upwards or downwards. |
...@@ -40,7 +41,7 @@ struct KeyEventExample { ...@@ -40,7 +41,7 @@ struct KeyEventExample {
build() { build() {
Column() { Column() {
Button('KeyEvent').backgroundColor(0x2788D9) Button('KeyEvent')
.onKeyEvent((event: KeyEvent) => { .onKeyEvent((event: KeyEvent) => {
if (event.type === KeyType.Down) { if (event.type === KeyType.Down) {
this.eventType = 'Down' this.eventType = 'Down'
...@@ -48,7 +49,7 @@ struct KeyEventExample { ...@@ -48,7 +49,7 @@ struct KeyEventExample {
if (event.type === KeyType.Up) { if (event.type === KeyType.Up) {
this.eventType = 'Up' this.eventType = 'Up'
} }
console.info(this.text = 'KeyType:' + this.eventType + '\nkeyCode:' + event.keyCode + '\nkeyText:' + event.keyText) this.text = 'KeyType:' + this.eventType + '\nkeyCode:' + event.keyCode + '\nkeyText:' + event.keyText
}) })
Text(this.text).padding(15) Text(this.text).padding(15)
}.height(300).width('100%').padding(35) }.height(300).width('100%').padding(35)
...@@ -56,4 +57,4 @@ struct KeyEventExample { ...@@ -56,4 +57,4 @@ struct KeyEventExample {
} }
``` ```
![en-us_image_0000001257058433](figures/en-us_image_0000001257058433.gif) ![keyEvent](figures/keyEvent.png)
...@@ -12,37 +12,43 @@ The show/hide event is triggered when a component is mounted or unmounted from t ...@@ -12,37 +12,43 @@ The show/hide event is triggered when a component is mounted or unmounted from t
| Name | Bubbling Supported| Description | | Name | Bubbling Supported| Description |
| ------------------------------------------------ | -------- | -------------------------- | | ------------------------------------------------ | -------- | -------------------------- |
| onAppear(event: () =&gt; void) | No | Triggered when the component is displayed.| | onAppear(event: () =&gt; void) | No | Triggered when the component is displayed.|
| onDisappear(event: () =&gt; void) | No | Triggered when the component disappears.| | onDisappear(event: () =&gt; void) | No | Triggered when the component is hidden. |
## Example ## Example
```ts ```ts
// xxx.ets // xxx.ets
import prompt from '@system.prompt' import prompt from '@ohos.prompt'
@Entry @Entry
@Component @Component
struct AppearExample { struct AppearExample {
@State isShow: boolean = true @State isShow: boolean = true
@State changeAppear: string = 'Hide Text'
private myText: string = 'Text for onAppear' private myText: string = 'Text for onAppear'
private changeAppear: string = 'Hide Text'
build() { build() {
Column() { Column() {
Button(this.changeAppear) Button(this.changeAppear)
.onClick(() => { .onClick(() => {
this.isShow = !this.isShow this.isShow = !this.isShow
}).margin(3).backgroundColor(0x2788D9) }).margin(15)
if (this.isShow) { if (this.isShow) {
Text(this.myText) Text(this.myText).fontSize(26).fontWeight(FontWeight.Bold)
.onAppear(() => { .onAppear(() => {
this.changeAppear = 'Show Text' this.changeAppear = 'Hide Text'
prompt.showToast({ message: 'The text is shown', duration: 2000 }) prompt.showToast({
message: 'The text is shown',
duration: 2000
})
}) })
.onDisAppear(() => { .onDisAppear(() => {
this.changeAppear = 'Hide Text' this.changeAppear = 'Show Text'
prompt.showToast({ message: 'The text is hidden', duration: 2000 }) prompt.showToast({
message: 'The text is hidden',
duration: 2000
})
}) })
} }
}.padding(30).width('100%') }.padding(30).width('100%')
...@@ -50,4 +56,4 @@ struct AppearExample { ...@@ -50,4 +56,4 @@ struct AppearExample {
} }
``` ```
![en-us_image_0000001211898468](figures/en-us_image_0000001211898468.gif) ![en-us_image_0000001219864151](figures/en-us_image_0000001219864151.gif)
...@@ -11,7 +11,7 @@ A touch event is triggered when a finger is pressed, slides, or is lifted from a ...@@ -11,7 +11,7 @@ A touch event is triggered when a finger is pressed, slides, or is lifted from a
| Name | Bubbling Supported| Description | | Name | Bubbling Supported| Description |
| ------------------------------------------------------------ | -------- | ------------------------------------------------------------ | | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ |
| onTouch(event: (event?: TouchEvent) =&gt; void) | Yes | Invoked when a touch action is triggered. For details about **event**, see [TouchEvent](#touchevent).| | onTouch(event: (event?: TouchEvent) =&gt; void) | Yes | Invoked when a touch event is triggered. For details about **event**, see [TouchEvent](#touchevent).|
## TouchEvent ## TouchEvent
...@@ -23,8 +23,8 @@ A touch event is triggered when a finger is pressed, slides, or is lifted from a ...@@ -23,8 +23,8 @@ A touch event is triggered when a finger is pressed, slides, or is lifted from a
| changedTouches | Array&lt;[TouchObject](#touchobject)&gt; | Finger information changed.| | changedTouches | Array&lt;[TouchObject](#touchobject)&gt; | Finger information changed.|
| stopPropagation | () => void | Stops the event from bubbling upwards or downwards.| | stopPropagation | () => void | Stops the event from bubbling upwards or downwards.|
| timestamp<sup>8+</sup> | number | Timestamp of the event. It is interval between the time when the event is triggered and the time when the system starts, in nanoseconds.| | timestamp<sup>8+</sup> | number | Timestamp of the event. It is interval between the time when the event is triggered and the time when the system starts, in nanoseconds.|
| target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md) | Display area of the element that triggers the gesture event.| | target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md#eventtarget8) | Display area of the element that triggers the gesture event.|
| source<sup>8+</sup> | [SourceType](ts-gesture-settings.md) | Event input device.| | source<sup>8+</sup> | [SourceType](ts-gesture-settings.md#sourcetype)| Event input device.|
## TouchObject ## TouchObject
...@@ -49,8 +49,8 @@ struct TouchExample { ...@@ -49,8 +49,8 @@ struct TouchExample {
@State eventType: string = '' @State eventType: string = ''
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) { Column() {
Button('Touch').backgroundColor(0x2788D9).height(40).width(80) Button('Touch').height(40).width(100)
.onTouch((event: TouchEvent) => { .onTouch((event: TouchEvent) => {
if (event.type === TouchType.Down) { if (event.type === TouchType.Down) {
this.eventType = 'Down' this.eventType = 'Down'
...@@ -61,15 +61,31 @@ struct TouchExample { ...@@ -61,15 +61,31 @@ struct TouchExample {
if (event.type === TouchType.Move) { if (event.type === TouchType.Move) {
this.eventType = 'Move' this.eventType = 'Move'
} }
console.info(this.text = 'TouchType:' + this.eventType + '\nDistance between touch point and touch element:\nx: ' this.text = 'TouchType:' + this.eventType + '\nDistance between touch point and touch element:\nx: '
+ event.touches[0].x + '\n' + 'y: ' + event.touches[0].y + '\ncomponent globalPos:(' + event.touches[0].x + '\n' + 'y: ' + event.touches[0].y + '\nComponent globalPos:('
+ event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\nwidth:' + event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\nwidth:'
+ event.target.area.width + '\nheight:' + event.target.area.height) + event.target.area.width + '\nheight:' + event.target.area.height
})
Button('Touch').height(50).width(200).margin(20)
.onTouch((event: TouchEvent) => {
if (event.type === TouchType.Down) {
this.eventType = 'Down'
}
if (event.type === TouchType.Up) {
this.eventType = 'Up'
}
if (event.type === TouchType.Move) {
this.eventType = 'Move'
}
this.text = 'TouchType:' + this.eventType + '\nDistance between touch point and touch element:\nx: '
+ event.touches[0].x + '\n' + 'y: ' + event.touches[0].y + '\nComponent globalPos:('
+ event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\nwidth:'
+ event.target.area.width + '\nheight:' + event.target.area.height
}) })
Text(this.text) Text(this.text)
}.height(200).width(350).padding({ left: 35, right: 35, top: 35 }) }.width('100%').padding(30)
} }
} }
``` ```
![en-us_image_0000001212058464](figures/en-us_image_0000001212058464.gif) ![en-us_image_0000001209874754](figures/en-us_image_0000001209874754.gif)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册