未验证 提交 58b156c2 编写于 作者: O openharmony_ci 提交者: Gitee

!3220 同步英文文档到release分支

Merge pull request !3220 from LiAn/OpenHarmony-3.1-Release
...@@ -22,16 +22,16 @@ ...@@ -22,16 +22,16 @@
## Available APIs ## Available APIs
| Module | API | Description | | Module| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ohos.sensor | sensor.on(sensorType,callback:AsyncCallback<Response>):void | Subscribes to data changes of a type of sensor. | | ohos.sensor | sensor.on(sensorType, callback:AsyncCallback<Response>): void | Subscribes to data changes of a type of sensor.|
| ohos.sensor | sensor.once(sensorType,callback:AsyncCallback<Response>):void | Subscribes to only one data change of a type of sensor. | | ohos.sensor | sensor.once(sensorType, callback:AsyncCallback<Response>): void | Subscribes to only one data change of a type of sensor.|
| ohos.sensor | sensor.off(sensorType,callback:AsyncCallback<void>):void | Unsubscribes from sensor data changes. | | ohos.sensor | sensor.off(sensorType, callback:AsyncCallback<void>): void | Unsubscribes from sensor data changes.|
## How to Develop ## How to Develop
1. To obtain data from a type of sensor, configure the request permissions in the **config.json** file. 1. To obtain data from a type of sensor, configure the request permissions in the **config.json** file.
``` ```
"reqPermissions":[ "reqPermissions":[
...@@ -67,67 +67,59 @@ ...@@ -67,67 +67,59 @@
"when":"inuse" "when":"inuse"
} }
}, },
{
"name":"ohos.permission.VIBRATE",
"reason"":"",
"usedScene":{
"ability": [".MainAbility"],
"when":"inuse"
}
},
] ]
``` ```
2. Subscribe to data changes of a type of sensor. 2. Subscribe to data changes of a type of sensor.
``` ```
import sensor from "@ohos.sensor" import sensor from "@ohos.sensor"
sensor.on(type:sensorType,function(error,data){ sensor.on(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data){
if (error) {// The call fails, and error.code and error.message are printed.
console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message);
return;
};
console.info("Subscription succeeded. data = "+ data);// The call is successful, and the obtained sensor data is printed. console.info("Subscription succeeded. data = "+ data);// The call is successful, and the obtained sensor data is printed.
} }
); );
``` ```
The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**. The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**.
![en-us_image_0000001241693881](figures/en-us_image_0000001241693881.png) ![en-us_image_0000001241693881](figures/en-us_image_0000001241693881.png)
3. Unsubscribe from sensor data changes. 3. Unsubscribe from sensor data changes.
``` ```
import sensor from "@ohos.sensor" import sensor from "@ohos.sensor"
sensor.off(type:sensorType,function(error) { sensor.off(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function() {
if (error) {// The unsubscription fails, and error.code and error.message are printed.
console.error("Failed to unsubscribe from acceleration sensor data. Error code: " + error.code + "; message: " + error.message);
return;
};
console.info("Succeeded in unsubscribing from acceleration sensor data.");// The unsubscription is successful, and the result is printed. console.info("Succeeded in unsubscribing from acceleration sensor data.");// The unsubscription is successful, and the result is printed.
} }
); );
``` ```
The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**. The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**.
![en-us_image_0000001196654004](figures/en-us_image_0000001196654004.png) ![en-us_image_0000001196654004](figures/en-us_image_0000001196654004.png)
4. Subscribe to only one data change of a type of sensor. 4. Subscribe to only one data change of a type of sensor.
``` ```
import sensor from "@ohos.sensor" import sensor from "@ohos.sensor"
sensor.once(tyep:sensorType,function(error, data) { sensor.once(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data) {
if (error) {// The call fails, and error.code and error.message are printed. console.info("Data obtained successfully. data=" + data);// The call is successful, and the obtained sensor data is printed.
console.error("Failed to obtain data. Error code: " + error.code + "; message: " + error.message);
return;
};
console.info("Data obtained successfully. data="+data);// The call is successful, and the obtained sensor data is printed.
} }
); );
``` ```
The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**. The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**.
![en-us_image_0000001241733907](figures/en-us_image_0000001241733907.png) ![en-us_image_0000001241733907](figures/en-us_image_0000001241733907.png)
If the API fails to be called, you are advised to use the **try/catch** statement to capture error information that may occur in the code. Example:
```
try {
sensor.once(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data) {
console.info("Data obtained successfully. data=" + data);// The call is successful, and the obtained sensor data is printed.
});
} catch (error) {
console.error(error);
}
```
...@@ -8,20 +8,20 @@ You can set different vibration effects as needed, for example, customizing vibr ...@@ -8,20 +8,20 @@ You can set different vibration effects as needed, for example, customizing vibr
## Available APIs ## Available APIs
| Module | API | Description | | Module| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ohos.vibrator | vibrate(duration: number): Promise<void> | Triggers vibration with the specified duration. This API uses a promise to return the result. | | ohos.vibrator | vibrate(duration: number): Promise<void> | Triggers vibration with the specified duration. This API uses a promise to return the result.|
| ohos.vibrator | vibrate(duration: number, callback?: AsyncCallback<void>): void | Triggers vibration with the specified duration. This API uses a callback to return the result. | | ohos.vibrator | vibrate(duration: number, callback?: AsyncCallback<void>): void | Triggers vibration with the specified duration. This API uses a callback to return the result.|
| ohos.vibrator | vibrate(effectId: EffectId): Promise<void> | Triggers vibration with the specified effect. This API uses a promise to return the result. | | ohos.vibrator | vibrate(effectId: EffectId): Promise<void> | Triggers vibration with the specified effect. This API uses a promise to return the result.|
| ohos.vibrator | vibrate(effectId: EffectId, callback?: AsyncCallback<void>): void | Triggers vibration with the specified effect. This API uses a callback to return the result. | | ohos.vibrator | vibrate(effectId: EffectId, callback?: AsyncCallback<void>): void | Triggers vibration with the specified effect. This API uses a callback to return the result.|
| ohos.vibrator | stop(stopMode: VibratorStopMode): Promise<void> | Stops vibration. This API uses a promise to return the result. | | ohos.vibrator | stop(stopMode: VibratorStopMode): Promise<void> | Stops vibration. This API uses a promise to return the result.|
| ohos.vibrator | stop(stopMode: VibratorStopMode, callback?: AsyncCallback<void>): void | Stops vibration. This API uses a callback to return the result. | | ohos.vibrator | stop(stopMode: VibratorStopMode, callback?: AsyncCallback<void>): void | Stops vibration. This API uses a callback to return the result.|
## How to Develop ## How to Develop
1. Declare the permissions required for controlling vibrators on the hardware device in the **config.json** file. 1. Declare the permissions required for controlling vibrators on the hardware device in the **config.json** file.
``` ```
"reqPermissions":[ "reqPermissions":[
{ {
...@@ -58,26 +58,26 @@ You can set different vibration effects as needed, for example, customizing vibr ...@@ -58,26 +58,26 @@ You can set different vibration effects as needed, for example, customizing vibr
``` ```
2. Trigger the device to vibrate. 2. Trigger the device to vibrate.
``` ```
import vibrator from "@ohos.vibrator" import vibrator from "@ohos.vibrator"
vibrator.vibrate(duration: number).then((error)=>{ vibrator.vibrate(1000).then((error)=>{
if(error){// The call fails, and error.code and error.message are printed. if (error) {// The call fails, and error.code and error.message are printed.
console.log("Promise return failed.error.code"+error.code+"error.message"+error.message); Console.log("Promise return failed.error.code"+error.code+"error.message"+error.message);
}else{// The call succeeded. The device starts to vibrate. }else{// The call is successful, and the device starts to vibrate.
console.log("Promise returned to indicate a successful vibration.") Console.log("Promise returned to indicate a successful vibration.")
}; };
}) })
``` ```
3. Stop the vibration. 3. Stop the vibration.
``` ```
import vibrator from "@ohos.vibrator" import vibrator from "@ohos.vibrator"
vibrator.stop(stopMode: VibratorStopMode).then((error)=>{ vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error)=>{
if(error){// The call fails, and error.code and error.message are printed. if (error) {// The call fails, and error.code and error.message are printed.
console.log("Promise return failed. error.code"+error.code+"error.message"+error.message); Console.log("Promise return failed.error.code"+error.code+"error.message"+error.message);
}else{// The call succeeded. The device stops vibration. }else{// The call is successful, and the device stops vibration.
Console.log("Promise returned to indicate a successful stop."); Console.log("Promise returned to indicate a successful stop.");
}; };
}) })
......
...@@ -6,10 +6,11 @@ The vibrator service opens up the latest capabilities of the vibrator hardware t ...@@ -6,10 +6,11 @@ The vibrator service opens up the latest capabilities of the vibrator hardware t
## Working Principles ## Working Principles
The vibrator is a Misc device that consists of four modules: Vibrator API, Vibrator Framework, Vibrator Service, and HD_IDL. The vibrator is a Misc device that consists of four modules: Vibrator API, Vibrator Framework, Vibrator Service, and HDF layer.
**Figure1** Vibrator in Misc devices **Figure 1** Vibrator in Misc devices
![en-us_image_0000001180249428](figures/en-us_image_0000001180249428.png)
![0752d302-aeb9-481a-bb8f-e5524eb61eeb](figures/0752d302-aeb9-481a-bb8f-e5524eb61eeb.png)
- Vibrator API: provides basic vibrator APIs, including the APIs for querying the vibrator list, querying the vibrator by effect, and triggering and stopping vibration. - Vibrator API: provides basic vibrator APIs, including the APIs for querying the vibrator list, querying the vibrator by effect, and triggering and stopping vibration.
...@@ -17,9 +18,9 @@ The vibrator is a Misc device that consists of four modules: Vibrator API, Vibra ...@@ -17,9 +18,9 @@ The vibrator is a Misc device that consists of four modules: Vibrator API, Vibra
- Vibrator Service: manages services of vibrators. - Vibrator Service: manages services of vibrators.
- HD_IDL: adapts to different devices. - HDF layer: adapts to different devices.
## Constraints ## Constraints
When using a vibrator, you need to declare and obtain the **ohos.permission.VIBRATE** permission first so that you can control the vibration effect. When using a vibrator, you must declare the **ohos.permission.VIBRATE** permission before you can control the vibration effect. The sensitivity level of this permission is **system_grant**.
...@@ -3,6 +3,9 @@ The **\<web>** component displays web page content. ...@@ -3,6 +3,9 @@ The **\<web>** component displays web page content.
>![](../../public_sys-resources/icon-note.gif) **NOTE** >![](../../public_sys-resources/icon-note.gif) **NOTE**
> This component is supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
ohos.permission.INTERNET, required only for accessing online web pages.
## Constraints ## Constraints
The **\<web>** component does not follow the transition animation. A page allows only one **\<web>** component. The **\<web>** component does not follow the transition animation. A page allows only one **\<web>** component.
...@@ -44,7 +47,7 @@ The following methods are supported. ...@@ -44,7 +47,7 @@ The following methods are supported.
``` ```
``` ```
<!-- xxx.js --> // xxx.js
export default { export default {
reloadWeb() { reloadWeb() {
this.$element('web').reload() this.$element('web').reload()
......
...@@ -48,7 +48,7 @@ Creates a date picker in the given date range. ...@@ -48,7 +48,7 @@ Creates a date picker in the given date range.
| Name| Type| Description| | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| year | number | Year of the selected date.| | year | number | Year of the selected date.|
| month | number | Month of the selected date.| | month | number | Month of the selected date. The value ranges from 0 to 11. The value **0** indicates January, and the value **11** indicates December. |
| day | number | Day of the selected date.| | day | number | Day of the selected date.|
......
...@@ -29,11 +29,11 @@ Creates a component that can automatically display the navigation bar, title, an ...@@ -29,11 +29,11 @@ Creates a component that can automatically display the navigation bar, title, an
| Name | Type | Default Value | Description | | Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| title | string \| [Custom Builder](../../ui/ts-types.md) | - | Page title. | | title | string \| [CustomBuilder](../../ui/ts-types.md)<sup>8+</sup> | - | Page title. |
| subtitle | string | - | Subtitle of the page. | | subtitle | string | - | Subtitle of the page. |
| menus | Array&lt;NavigationMenuItem&gt; \| [Custom Builder](../../ui/ts-types.md) | - | Menu in the upper right corner of the page. | | menus | Array&lt;NavigationMenuItem&gt; \| [CustomBuilder](../../ui/ts-types.md)<sup>8+</sup> | - | Menu in the upper right corner of the page. |
| titleMode | NavigationTitleMode | NavigationTitleMode.Free | Display mode of the page title bar. | | titleMode | NavigationTitleMode | NavigationTitleMode.Free | Display mode of the page title bar. |
| toolBar | {<br/>items:[<br/>Object<br/>] }<br/>\| [Custom Builder](../../ui/ts-types.md) | - | Content of the toolbar.<br/>**items**: all items on the toolbar. | | toolBar | {<br/>items:[<br/>Object<br/>] }<br/>\| [CustomBuilder](../../ui/ts-types.md)<sup>8+</sup> | - | Content of the toolbar.<br/>**items**: all items on the toolbar. |
| hideToolBar | boolean | false | Whether to hide the toolbar.<br/>**true**: Hide the toolbar.<br/>**false**: Show the toolbar. | | hideToolBar | boolean | false | Whether to hide the toolbar.<br/>**true**: Hide the toolbar.<br/>**false**: Show the toolbar. |
| hideTitleBar | boolean | false | Whether to hide the title bar. | | hideTitleBar | boolean | false | Whether to hide the title bar. |
| hideBackButton | boolean | false | Whether to hide the back button. | | hideBackButton | boolean | false | Whether to hide the back button. |
...@@ -67,7 +67,7 @@ Creates a component that can automatically display the navigation bar, title, an ...@@ -67,7 +67,7 @@ Creates a component that can automatically display the navigation bar, title, an
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| onTitleModeChanged(callback: (titleMode: NavigationTitleMode) =&gt; void) | Triggered when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls. | | onTitleModeChange(callback:&nbsp;(titleMode:&nbsp;NavigationTitleMode)&nbsp;=&gt;&nbsp;void) | Triggered when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls. |
## Example ## Example
...@@ -140,7 +140,7 @@ struct NavigationExample { ...@@ -140,7 +140,7 @@ struct NavigationExample {
.titleMode(NavigationTitleMode.Free) .titleMode(NavigationTitleMode.Free)
.hideTitleBar(false) .hideTitleBar(false)
.hideBackButton(false) .hideBackButton(false)
.onTitleModeChanged((titleModel: NavigationTitleMode) => { .onTitleModeChange((titleModel: NavigationTitleMode) => {
console.log('titleMode') console.log('titleMode')
}) })
.toolBar({ items: [ .toolBar({ items: [
......
...@@ -22,7 +22,7 @@ RichText\(content:string\) ...@@ -22,7 +22,7 @@ RichText\(content:string\)
| Name| Type| Mandatory| Default Value| Description| | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| content | string | Yes| - | String in HTML format.| | content | string | Yes| - | String in HTML format.|
## Events ## Events
...@@ -41,8 +41,8 @@ RichText\(content:string\) ...@@ -41,8 +41,8 @@ RichText\(content:string\)
| \<br/> | Inserts a newline character.| \<p>This is a paragraph\<br/>This is a new paragraph\</p>| | \<br/> | Inserts a newline character.| \<p>This is a paragraph\<br/>This is a new paragraph\</p>|
| \<hr/> | Defines a thematic break (such as a shift of topic) on an HTML page and creates a horizontal line.| \<p>This is a paragraph\</p>\<hr/>\<p>This is a paragraph\</p> | | \<hr/> | Defines a thematic break (such as a shift of topic) on an HTML page and creates a horizontal line.| \<p>This is a paragraph\</p>\<hr/>\<p>This is a paragraph\</p> |
| \<div>\</div> | Defines a generic container that is generally used to group block-level elements. It allows you to apply CSS styles to multiple elements at the same time.| \<div style='color:#0000FF'>\<h3>This is the heading in a div element\</h3>\</div> | | \<div>\</div> | Defines a generic container that is generally used to group block-level elements. It allows you to apply CSS styles to multiple elements at the same time.| \<div style='color:#0000FF'>\<h3>This is the heading in a div element\</h3>\</div> |
| \<i>\</i> | Displays text in italic style.| \<p>\<i>This is in italic style\</i>\</p> | | \<i>\</i> | Displays text in italic style.| \<i>This is in italic style\</i> |
| \<u>\</u> | Defines text that should be styled differently or have a non-textual annotation, such as misspelt words or a proper name in Chinese text. It is recommended that you avoid using the \<u> tag where it could be confused with a hyperlink.| \<p>This is an underlined paragraph\</p>| | \<u>\</u> | Defines text that should be styled differently or have a non-textual annotation, such as misspelt words or a proper name in Chinese text. It is recommended that you avoid using the \<u> tag where it could be confused with a hyperlink.| \<p>\<u>This is an underlined paragraph\<u>\<p> |
| \<style>\</style> | Used to embed CSS within an HTML document.| \<style>h1{color:red;}p{color:blue;}\</style> | | \<style>\</style> | Used to embed CSS within an HTML document.| \<style>h1{color:red;}p{color:blue;}\</style> |
| style | Defines the inline style of an element and is placed inside the tag. Use quotation marks (') to separate the styling text and use semicolons (;) to separate styles, for example, **style='width: 500px;height: 500px;border: 1px solid;margin: 0 auto;'**.| \<h1 style='color:blue;text-align:center'>This is a heading\</h1>\<p style='color:green'>This is a paragraph\</p> | | style | Defines the inline style of an element and is placed inside the tag. Use quotation marks (') to separate the styling text and use semicolons (;) to separate styles, for example, **style='width: 500px;height: 500px;border: 1px solid;margin: 0 auto;'**.| \<h1 style='color:blue;text-align:center'>This is a heading\</h1>\<p style='color:green'>This is a paragraph\</p> |
| \<script>\</script> | Used to embed or reference a client-side script, such as JavaScript.| \<script>document.write("Hello World!")\</script> | | \<script>\</script> | Used to embed or reference a client-side script, such as JavaScript.| \<script>document.write("Hello World!")\</script> |
......
...@@ -20,9 +20,9 @@ This component can contain a single child component. ...@@ -20,9 +20,9 @@ This component can contain a single child component.
## APIs ## APIs
ScrollBar(value: ScrollBarOption) ScrollBar(value: ScrollBarOptions)
- ScrollBarOption parameters - ScrollBarOptions parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| scroller | [Scroller](ts-container-scroll.md#scroller) | Yes | - | Scroller, which can be bound to and control scrollable components. | | scroller | [Scroller](ts-container-scroll.md#scroller) | Yes | - | Scroller, which can be bound to and control scrollable components. |
......
...@@ -31,7 +31,7 @@ Search(options?: { value?: string; placeholder?: string; icon?: string; controll ...@@ -31,7 +31,7 @@ Search(options?: { value?: string; placeholder?: string; icon?: string; controll
| Name| Type| Default Value| Description| | Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| 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](../../ui/ts-types.md#ResourceColor) | - | Placeholder text color.| | placeholderColor | [ResourceColor](../../ui/ts-types.md) | - | Placeholder text color.|
| placeholderFont | [Font](../../ui/ts-types.md) | - | Placeholder text style.| | placeholderFont | [Font](../../ui/ts-types.md) | - | Placeholder text style.|
| textFont | [Font](../../ui/ts-types.md) | - | Text font for the search text box.| | textFont | [Font](../../ui/ts-types.md) | - | Text font for the search text box.|
......
...@@ -20,8 +20,8 @@ Select(options: Array<SelectOption>) ...@@ -20,8 +20,8 @@ Select(options: Array<SelectOption>)
| Name| Type| Mandatory| Default Value| Description| | Name| Type| Mandatory| Default Value| Description|
| ------ | ----------------------------------------------- | ---- | ------ | -------------- | | ------ | ----------------------------------------------- | ---- | ------ | -------------- |
| value | [ResourceStr](../../ui/ts-types.md#ResourceStr) | Yes| - | Value of an option in the drop-down list box.| | value | [ResourceStr](../../ui/ts-types.md) | Yes| - | Value of an option in the drop-down list box.|
| icon | [ResourceStr](../../ui/ts-types.md#ResourceStr) | No| - | Icon of an option in the drop-down list box.| | icon | [ResourceStr](../../ui/ts-types.md) | No| - | Icon of an option in the drop-down list box.|
## Attributes ## Attributes
...@@ -29,20 +29,20 @@ Select(options: Array<SelectOption>) ...@@ -29,20 +29,20 @@ Select(options: Array<SelectOption>)
| ----------------------- | --------------------------------------------------- | ------ | ----------------------------------------------- | | ----------------------- | --------------------------------------------------- | ------ | ----------------------------------------------- |
| selected | number | - | Index of the initial selected option in the drop-down list box. The index of the first option is **0**.| | selected | number | - | Index of the initial selected option in the drop-down list box. The index of the first option is **0**.|
| value | string | - | Text of the drop-down button.| | value | string | - | Text of the drop-down button.|
| font | [Font](../../ui/ts-types.md) | - | Text font of the drop-down button.| | font | [Font](../../ui/ts-types.md) | - | Text font of the drop-down button.|
| fontColor | [ResourceColor](../../ui/ts-types.md#ResourceColor) | - | Text color of the drop-down button.| | fontColor | [ResourceColor](../../ui/ts-types.md) | - | Text color of the drop-down button.|
| selectedOptionBgColor | [ResourceColor](../../ui/ts-types.md#ResourceColor) | - | Background color of the selected option in the drop-down list box.| | selectedOptionBgColor | [ResourceColor](../../ui/ts-types.md) | - | Background color of the selected option in the drop-down list box.|
| selectedOptionFont | [Font](../../ui/ts-types.md) | - | Text font of the selected option in the drop-down list box.| | selectedOptionFont | [Font](../../ui/ts-types.md) | - | Text font of the selected option in the drop-down list box.|
| selectedOptionFontColor | [ResourceColor](../../ui/ts-types.md#ResourceColor) | - | Text color of the selected option in the drop-down list box.| | selectedOptionFontColor | [ResourceColor](../../ui/ts-types.md) | - | Text color of the selected option in the drop-down list box.|
| optionBgColor | [ResourceColor](../../ui/ts-types.md#ResourceColor) | - | Background color of an option in the drop-down list box.| | optionBgColor | [ResourceColor](../../ui/ts-types.md) | - | Background color of an option in the drop-down list box.|
| optionFont | [Font](../../ui/ts-types.md) | - | Text font of an option in the drop-down list box.| | optionFont | [Font](../../ui/ts-types.md) | - | Text font of an option in the drop-down list box.|
| optionFontColor | [ResourceColor](../../ui/ts-types.md#ResourceColor) | - | Text color of an option in the drop-down list box.| | optionFontColor | [ResourceColor](../../ui/ts-types.md) | - | Text color of an option in the drop-down list box.|
## Events ## Events
| Name| Description| | Name| Description|
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| onSelected(callback: (index: number, value?:string) => void)| Invoked when an option in the drop-down list box is selected. **index** indicates the index of the selected option. **value** indicates the value of the selected option.| | onSelect(callback: (index: number, value?:string) => void) | Invoked when an option in the drop-down list box is selected. **index** indicates the index of the selected option. **value** indicates the value of the selected option.|
## Example ## Example
...@@ -61,7 +61,7 @@ struct SliderExample { ...@@ -61,7 +61,7 @@ struct SliderExample {
.font({size: 30, weight:400, family: 'serif', style: FontStyle.Normal }) .font({size: 30, weight:400, family: 'serif', style: FontStyle.Normal })
.selectedOptionFont({size: 40, weight: 500, family: 'serif', style: FontStyle.Normal }) .selectedOptionFont({size: 40, weight: 500, family: 'serif', style: FontStyle.Normal })
.optionFont({size: 30, weight: 400, family: 'serif', style: FontStyle.Normal }) .optionFont({size: 30, weight: 400, family: 'serif', style: FontStyle.Normal })
.onSelected((index:number)=>{ .onSelecte((index:number)=>{
console.info("Select:" + index) console.info("Select:" + index)
}) })
} }
......
...@@ -31,7 +31,7 @@ TextArea(value?:{placeholder?: string controller?: TextAreaController}) ...@@ -31,7 +31,7 @@ TextArea(value?:{placeholder?: string controller?: TextAreaController})
## Attributes ## Attributes
In addition to [universal attributes](ts-universal-attributes.md), the following attributes are supported. In addition to [universal attributes](ts-universal-attributes-index.md), the following attributes are supported.
| Name | Type | Default Value | Description | | Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
...@@ -49,15 +49,6 @@ In addition to [universal attributes](ts-universal-attributes.md), the following ...@@ -49,15 +49,6 @@ In addition to [universal attributes](ts-universal-attributes.md), the following
| End | Align the tail horizontally. | | End | Align the tail horizontally. |
### TextAreaController<sup>8+</sup>
Defines the controller for controlling the **&lt;TextArea&gt;** component.
| Name | Description |
| -------- | -------- |
| caretPosition(value: number): void | Position of the input cursor.<br/>**value**: indicates the length from the start of the string to the position where the input cursor is located. |
## Events ## Events
| Name | Description | | Name | Description |
...@@ -67,6 +58,28 @@ Defines the controller for controlling the **&lt;TextArea&gt;** component. ...@@ -67,6 +58,28 @@ Defines the controller for controlling the **&lt;TextArea&gt;** component.
| 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>
Defines the controller for controlling the **&lt;TextArea&gt;** component.
### Objects to Import
```
controller: TextAreaController = new TextAreaController()
```
### caretPosition<sup>8+</sup>
caretPosition(value: number): void
Sets the position of the caret.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ------------------- |
| value | number | Yes | - | Length from the start of the string to the position where the input cursor is located. |
## Example ## Example
......
...@@ -18,32 +18,46 @@ TextClock(options?: {timeZoneOffset?: number, contorller?: TextClockController}) ...@@ -18,32 +18,46 @@ TextClock(options?: {timeZoneOffset?: number, contorller?: TextClockController})
- Parameters - Parameters
| Name| Type| Mandatory| Default Value| Description| | Name | Type| Mandatory| Default Value | Description |
| -------- | -------- | ---- | ------------------ | ------------------------------------------------------------ | | -------- | -------- | ---- | ------------------ | ------------------------------------------------------------ |
| timeZoneOffset | number | No| Time zone offset| Sets the time zone offset. The value range is [-14, 12], indicating UTC+12 to UTC-12. A negative value indicates Eastern Standard Time, and a positive value indicates Western Standard Time. For example, **-8** indicates UTC+8. For countries or regions crossing the International Date Line, use -13 (UTC+13) and -14 (UTC+14) to ensure consistent time within the entire country or region.| | timeZoneOffset | number | No | Time zone offset| Sets the time zone offset. The value range is [-14, 12], indicating UTC+12 to UTC-12. A negative value indicates Eastern Standard Time, and a positive value indicates Western Standard Time. For example, **-8** indicates UTC+8. For countries or regions crossing the International Date Line, use -13 (UTC+13) and -14 (UTC+14) to ensure consistent time within the entire country or region.|
| contorller | [TextClockContorller](#TextClockController) | No| null | Binds a controller to control the status of the **<TextClock\>** component.| | contorller | [TextClockContorller](#TextClockController) | No| null | Binds a controller to control the status of the **<TextClock\>** component.|
## Attributes ## Attributes
| Name| Type| Default Value| Description| | Name | Type| Default Value | Description |
| ------ | -------- | -------- | ------------------------------------------------------------ | | ------ | -------- | -------- | ------------------------------------------------------------ |
| format | string | 'hhmmss' | Time format, for example, **yyyy/mm/dd** or **yyyy-mm-dd**. Supported time format strings: <ul><li>yyyy (year)</li> <li>mm (two-letter abbreviated month name)</li> <li>mmm (three-letter abbreviated month name)</li> <li>mmmm (full month name)</li> <li>dd (two-letter abbreviated day of the week)</li> <li>ddd (three-letter abbreviated day of the week)</li> <li>dddd (full day of the week)</li> <li>HH (24-hour format)</li> <li>hh (12-hour format)</li> <li>MM/mm (minute)</li> <li>SS/ss (second)</li></ul>| | format | string | 'hhmmss' | Time format, for example, **yyyy/mm/dd** or **yyyy-mm-dd**. Supported time format strings: <ul><li>yyyy (year)</li> <li>mm (two-letter abbreviated month name)</li> <li>mmm (three-letter abbreviated month name)</li> <li>mmmm (full month name)</li> <li>dd (two-letter abbreviated day of the week)</li> <li>ddd (three-letter abbreviated day of the week)</li> <li>dddd (full day of the week)</li> <li>HH (24-hour format)</li> <li>hh (12-hour format)</li> <li>MM/mm (minute)</li> <li>SS/ss (second)</li></ul>|
## Events
| Name | Description |
| -------------------------------------------- | ------------------------------------------------------------ |
| onDateChange(event: (value: number) => void) | Triggered when the time changes in seconds at minimum.<br> **value**: Unix time stamp, which is the number of milliseconds that have elapsed since the Unix epoch.|
## TextClockController ## TextClockController
Controller of the **<TextClock\>** component, which can be bound to the component for status control. Controller of the **<TextClock\>** component, which can be bound to the component for status control.
| API| Description| ### Objects to Import
| -------------------------------------------- | ------------------------------------------------------------ |
| start() | Starts the **<TextClock\>** component.|
| stop() | Stops the **<TextClock\>** component.|
```
controller: TextClockController = new TextClockController()
## Events ```
### start
start()
Starts the **<TextClock\>** component.
### stop
stop()
Stops the **<TextClock\>** component.
| Name| Description|
| -------------------------------------------- | ------------------------------------------------------------ |
| onDateChange(event: (value: number) => void) | Triggered when the time changes in seconds at minimum. <br /> value: Unix time stamp, which is the number of milliseconds that have elapsed since the Unix epoch.|
## Example ## Example
......
...@@ -31,7 +31,7 @@ TextInput(value?:{placeholder?: string controller?: TextInputController}) ...@@ -31,7 +31,7 @@ TextInput(value?:{placeholder?: string controller?: TextInputController})
## Attributes ## Attributes
In addition to [universal attributes](ts-universal-attributes.md), the following attributes are supported. In addition to [universal attributes](ts-universal-attributes-index.md), the following attributes are supported.
| Name | Type | Default Value | Description | | Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
...@@ -96,7 +96,8 @@ Sets the cursor in a specified position. ...@@ -96,7 +96,8 @@ Sets the cursor in a specified position.
| -------- | -------- | | -------- | -------- |
| onChange(value: string) =&gt; void | Triggered when the input changes. | | onChange(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 physical or soft keyboard is pressed. |
| onEditChanged(callback: (isEditing: boolean) =&gt; void) | Triggered when the input status changes. | | onEditChanged(callback:&nbsp;(isEditing:&nbsp;boolean)&nbsp;=&gt;&nbsp;void)<sup>(deprecated) </sup> | Triggered when the input status changes. |
| onEditChange(callback:&nbsp;(isEditing:&nbsp;boolean)&nbsp;=&gt;&nbsp;void) <sup>8+</sup> | Triggered when the input status changes. |
| 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. |
......
...@@ -23,36 +23,54 @@ None ...@@ -23,36 +23,54 @@ None
TextTimer(options: { isCountDown?: boolean, count?: number, controller?: TextTimerController }) TextTimer(options: { isCountDown?: boolean, count?: number, controller?: TextTimerController })
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| isCountDown | boolean | No | false | Whether to count down. | | isCountDown | boolean | No | false | Whether to count down. |
| count | number | No | 60000 | Countdown time, in milliseconds. This parameter is valid only when **isCountDown** is set to **true**.<br/>- If the value of **count** is less than or equal to 0, the default value is used.<br/>- If the value of **count** is greater than 0, it is used. | | count | number | No | 60000 | Countdown time, in milliseconds. This parameter is valid only when **isCountDown** is set to **true**.<br/>- If the value of **count** is less than or equal to 0, the default value is used.<br/>- If the value of **count** is greater than 0, it is used. |
| controller | [TextTimerController](#texttimercontroller) | No | null | **&lt;TextTimer&gt;** controller. | | controller | [TextTimerController](#texttimercontroller) | No | null | **&lt;TextTimer&gt;** controller. |
## Attributes
### TextTimerController | Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| format | string | 'hh:mm:ss.ms' | Custom format. The value must contain at least one of the following keywords: **hh**, **mm**, **ss**, and **ms**. |
Defines the controller for controlling the **&lt;TextTimer&gt;** component.
| Name | Description | ## Events
| Name | Description |
| -------- | -------- | | -------- | -------- |
| start() | Starts the timer. | | onTimer(callback: (utc: number, elapsedTime: number) =&gt; void) | Triggered when the time text changes.<br/>**utc**: currently displayed time, in milliseconds.<br/>**elapsedTime**: elapsed time of the timer, in milliseconds. |
| pause() | Pauses the timer. |
| reset() | Resets the timer. |
## Attributes ## TextTimerController
| Name | Type | Default Value | Description | Defines the controller for controlling the **&lt;TextTimer&gt;** component.
| -------- | -------- | -------- | -------- |
| format | string | 'hh:mm:ss.ms' | Custom format. The value must contain at least one of the following keywords: **hh**, **mm**, **ss**, and **ms**. |
### Objects to Import
## Events ```
textTimerController: TextTimerController = new TextTimerController()
| Name | Description | ```
| -------- | -------- |
| onTimer(callback: (utc: number, elapsedTime: number) =&gt; void) | Triggered when the time text changes.<br/>**utc**: currently displayed time, in milliseconds.<br/>**elapsedTime**: elapsed time of the timer, in milliseconds. | ### start
start()
Starts the timer.
### pause
pause()
Pauses the timer.
### reset
reset()
Resets the timer.
## Example ## Example
...@@ -62,12 +80,12 @@ Defines the controller for controlling the **&lt;TextTimer&gt;** component. ...@@ -62,12 +80,12 @@ Defines the controller for controlling the **&lt;TextTimer&gt;** component.
@Entry @Entry
@Component @Component
struct TextTimerExample { struct TextTimerExample {
myTimerController: TextTimerController = new TextTimerController() textTimerController: TextTimerController = new TextTimerController()
@State format: string = 'hh:mm:ss.ms' @State format: string = 'hh:mm:ss.ms'
build() { build() {
Column() { Column() {
TextTimer({controller: this.myTimerController}) TextTimer({controller: this.textTimerController})
.format(this.format) .format(this.format)
.fontColor(Color.Black) .fontColor(Color.Black)
.fontSize(this.textSize) .fontSize(this.textSize)
...@@ -76,13 +94,13 @@ struct TextTimerExample { ...@@ -76,13 +94,13 @@ struct TextTimerExample {
}) })
Row() { Row() {
Button("start").onClick(() => { Button("start").onClick(() => {
this.myTimerController.start(); this.textTimerController.start();
}); });
Button("pause").onClick(() => { Button("pause").onClick(() => {
this.myTimerController.pause(); this.textTimerController.pause();
}); });
Button("reset").onClick(() => { Button("reset").onClick(() => {
this.myTimerController.reset(); this.textTimerController.reset();
}); });
} }
} }
......
...@@ -15,25 +15,25 @@ None ...@@ -15,25 +15,25 @@ None
LongPressGesture(options?: { fingers?: number, repeat?: boolean, duration?: number }) LongPressGesture(options?: { fingers?: number, repeat?: boolean, duration?: number })
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| fingers | number | No | 1 | Minimum number of fingers to trigger a long press gesture. The value ranges from 1 to 10. | | fingers | number | No | 1 | Minimum number of fingers to trigger a long press gesture. The value ranges from 1 to 10. |
| repeat | boolean | No | false | Whether to continuously trigger the event callback. | | repeat | boolean | No | false | Whether to continuously trigger the event callback. |
| duration | number | No | 500 | Minimum hold-down time, in ms. | | duration | number | No | 500 | Minimum hold-down time, in ms. |
## Events ## Events
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| onAction((event?: LongPressGestureEvent) =&gt; void) | Callback invoked when a long press gesture is recognized. | | onAction((event?: GestureEvent) =&gt; void) | Callback invoked when a long press gesture is recognized. |
| onActionEnd((event?: LongPressGestureEvent) =&gt; void) | Callback invoked when the finger used for a long press gesture is lift. | | onActionEnd((event?: GestureEvent) =&gt; void) | Callback 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) | Callback invoked when a tap cancellation event is received after a long press gesture is recognized. |
- LongPressGestureEvent<sup>8+</sup> attributes - GestureEvent attributes related to the long press gesture
| Name | Type | Description | | Name | Type | Description |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| repeat | boolean | Whether the event is repeated. | | repeat | boolean | Whether the event is repeated. |
## Example ## Example
...@@ -53,7 +53,7 @@ struct LongPressGestureExample { ...@@ -53,7 +53,7 @@ struct LongPressGestureExample {
.gesture( .gesture(
LongPressGesture({ repeat: true }) LongPressGesture({ repeat: true })
// Repeatedly triggered when the long press gesture exists. // Repeatedly triggered when the long press gesture exists.
.onAction((event: LongPressGestureEvent) => { .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.
......
...@@ -12,59 +12,59 @@ None ...@@ -12,59 +12,59 @@ None
## APIs ## APIs
PanGesture(options?: { fingers?: number, direction?: PanDirection, distance?: number } | [PanGestureOption](#pangestureoption)) PanGesture(options?: { fingers?: number, direction?: PanDirection, distance?: number } | [PanGestureOption](#pangestureoptions))
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| fingers | number | No | 1 | Minimum number of fingers to trigger a long press gesture. The value ranges from 1 to 10. | | fingers | number | No | 1 | Minimum number of fingers to trigger a long press gesture. The value ranges from 1 to 10. |
| direction | PanDirection | No | All | Slide direction. The enumerated value supports the AND (&amp;) and OR (\|) operations. | | direction | PanDirection | No | All | Slide direction. The enumerated value supports the AND (&amp;) and OR (\|) operations. |
| distance | number | No | 5.0 | Minimum slide recognition distance, in vp. | | distance | number | No | 5.0 | Minimum slide recognition distance, in vp. |
- PanDirection enums - PanDirection enums
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| All | All directions. | | All | All directions. |
| Horizontal | Horizontal slide. | | Horizontal | Horizontal slide. |
| Vertical | Vertical slide. | | Vertical | Vertical slide. |
| Left | Slide to the left. | | Left | Slide to the left. |
| Right | Slide to the right. | | Right | Slide to the right. |
| Up | Slide up. | | Up | Slide up. |
| Down | Slide down. | | Down | Slide down. |
| None | Slide disabled. | | None | Slide disabled. |
### PanGestureOption ### PanGestureOptions
The attributes of the slide gesture recognizer can be dynamically modified using the **PanGestureOption** AP. This avoids modifying attributes through status variables, which will cause the UI to be refreshed. The attributes of the slide gesture recognizer can be dynamically modified using the **PanGestureOptions** AP. This avoids modifying attributes through status variables, which will cause the UI to be refreshed.
PanGestureOption(options?: { fingers?: number, direction?: PanDirection, distance?: number }) PanGestureOptions(options?: { fingers?: number, direction?: PanDirection, distance?: number })
- Parameters - Parameters
For details, see **PanGesture**. For details, see **PanGesture**.
- APIs - APIs
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| setDirection(value: PanDirection) | Sets the direction. | | setDirection(value: PanDirection) | Sets the direction. |
| setDistance(value: number) | Sets the distance. | | setDistance(value: number) | Sets the distance. |
| setFingers(value: number) | Sets the number of fingers. | | setFingers(value: number) | Sets the number of fingers. |
## Events ## Events
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| onActionStart(callback: (event?: PanGestureEvent) =&gt; void) | Callback for the pan gestures reorganization event. | | onActionStart(callback: (event?: GestureEvent) =&gt; void) | Callback for the pan gestures reorganization event. |
| onActionUpdate(callback: (event?: PanGestureEvent) =&gt; void) | Callback invoked when a pan gesture is recognized. | | onActionUpdate(callback: (event?: GestureEvent) =&gt; void) | Callback invoked when a pan gesture is recognized. |
| onActionEnd(callback: (event?: PanGestureEvent) =&gt; void) | Callback invoked when the finger used for a pan gesture is lift. | | onActionEnd(callback: (event?: GestureEvent) =&gt; void) | Callback invoked when the finger used for a pan gesture is lift. |
| onActionCancel(callback: () =&gt; void) | Callback invoked when a tap cancellation event is received after a pan gesture is recognized. | | onActionCancel(callback: () =&gt; void) | Callback invoked when a tap cancellation event is received after a pan gesture is recognized. |
- PanGestureEvent<sup>8+</sup> attributes - GestureEvent attributes related to the pan gesture
| Name | Type | Description | | Name | Type | Description |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| offsetX | number | Offset of the gesture event, in vp. | | offsetX | number | Offset of the gesture event, in vp. |
| offsetY | number | Offset of the gesture event, in vp. | | offsetY | number | Offset of the gesture event, in vp. |
## Example ## Example
...@@ -85,10 +85,10 @@ struct PanGestureExample { ...@@ -85,10 +85,10 @@ struct PanGestureExample {
.translate({ x: this.offsetX, y: this.offsetY, z: 5 }) .translate({ x: this.offsetX, y: this.offsetY, z: 5 })
.gesture( .gesture(
PanGesture({}) PanGesture({})
.onActionStart((event: PanGestureEvent) => { .onActionStart((event: GestureEvent) => {
console.info('Pan start') console.info('Pan start')
}) })
.onActionUpdate((event: PanGestureEvent) => { .onActionUpdate((event: GestureEvent) => {
this.offsetX = event.offsetX this.offsetX = event.offsetX
this.offsetY = event.offsetY this.offsetY = event.offsetY
}) })
......
...@@ -15,27 +15,27 @@ None ...@@ -15,27 +15,27 @@ None
PinchGesture(options?: { fingers?: number, distance?: number }) PinchGesture(options?: { fingers?: number, distance?: number })
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| fingers | number | No | 2 | Minimum number of fingers to trigger a pinch. The value ranges from 2 to 5. | | fingers | number | No | 2 | Minimum number of fingers to trigger a pinch. The value ranges from 2 to 5. |
| distance | number | No | 3.0 | Minimum recognition distance, in vp. | | distance | number | No | 3.0 | Minimum recognition distance, in vp. |
## Events ## Events
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| onActionStart((event?: PinchGestureEvent) =&gt; void) | Callback invoked when a pinch gesture is recognized. | | onActionStart((event?: GestureEvent) =&gt; void) | Callback invoked when a pinch gesture is recognized. |
| onActionUpdate((event?: PinchGestureEvent) =&gt; void) | Callback invoked during the movement of a pinch gesture. | | onActionUpdate((event?: GestureEvent) =&gt; void) | Callback invoked during the movement of a pinch gesture. |
| onActionEnd((event?: PinchGestureEvent) =&gt; void) | Callback invoked when the finger used for a pinch gesture is lift. | | onActionEnd((event?: GestureEvent) =&gt; void) | Callback invoked when the finger used for a pinch gesture is lift. |
| onActionCancel(event: () =&gt; void) | Callback invoked when a tap cancellation event is received after a pinch gesture is recognized. | | onActionCancel(event: () =&gt; void) | Callback invoked when a tap cancellation event is received after a pinch gesture is recognized. |
- PinchGestureEvent<sup>8+</sup> attributes - GestureEvent attributes related to the pinch gesture
| Name | Type | Description | | Name | Type | Description |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| scale | number | Scale ratio. This attribute is used for the pinch gesture. | | scale | number | Scale ratio. This attribute is used for the pinch gesture. |
| pinchCenterX | number | X-coordinate of the center of the pinch gesture, in px. | | pinchCenterX | number | X-coordinate of the center of the pinch gesture, in px. |
| pinchCenterY | number | Y-coordinate of the center of the pinch gesture, in px. | | pinchCenterY | number | Y-coordinate of the center of the pinch gesture, in px. |
## Example ## Example
...@@ -55,10 +55,10 @@ struct PinchGestureExample { ...@@ -55,10 +55,10 @@ struct PinchGestureExample {
.scale({ x: this.scale, y: this.scale, z: this.scale }) .scale({ x: this.scale, y: this.scale, z: this.scale })
.gesture( .gesture(
PinchGesture() PinchGesture()
.onActionStart((event: PinchGestureEvent) => { .onActionStart((event: GestureEvent) => {
console.info('Pinch start') console.info('Pinch start')
}) })
.onActionUpdate((event: PinchGestureEvent) => { .onActionUpdate((event: GestureEvent) => {
this.scale = event.scale this.scale = event.scale
}) })
.onActionEnd(() => { .onActionEnd(() => {
......
...@@ -15,25 +15,25 @@ None ...@@ -15,25 +15,25 @@ None
RotationGesture(options?: { fingers?: number, angle?: number }) RotationGesture(options?: { fingers?: number, angle?: number })
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| fingers | number | No | 2 | Minimum number of fingers to trigger a rotation. The value ranges from 2 to 5. | | fingers | number | No | 2 | Minimum number of fingers to trigger a rotation. The value ranges from 2 to 5. |
| angle | number | No | 1.0 | Minimum degree that can trigger the rotation gesture. | | angle | number | No | 1.0 | Minimum degree that can trigger the rotation gesture. |
## Events ## Events
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| onActionStart((event?: RotationGestureEvent) =&gt; void) | Callback invoked when a rotation gesture is recognized. | | onActionStart((event?: GestureEvent) =&gt; void) | Callback invoked when a rotation gesture is recognized. |
| onActionUpdate((event?: RotationGestureEvent) =&gt; void) | Callback invoked during the movement of the rotation gesture. | | onActionUpdate((event?: GestureEvent) =&gt; void) | Callback invoked during the movement of the rotation gesture. |
| onActionEnd((event?: RotationGestureEvent) =&gt; void) | Callback invoked when the finger used for the rotation gesture is lift. | | onActionEnd((event?: GestureEvent) =&gt; void) | Callback invoked when the finger used for the rotation gesture is lift. |
| onActionCancel(event: () =&gt; void) | Callback invoked when a tap cancellation event is received after the rotation gesture is recognized. | | onActionCancel(event: () =&gt; void) | Callback invoked when a tap cancellation event is received after the rotation gesture is recognized. |
- RotationGestureEvent<sup>8+</sup> attributes - GestureEvent attributes related to the rotation gesture
| Name | Type | Description | | Name | Type | Description |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| angle | number | Rotation angle. | | angle | number | Rotation angle. |
## Example ## Example
...@@ -53,10 +53,10 @@ struct RotationGestureExample { ...@@ -53,10 +53,10 @@ struct RotationGestureExample {
.margin(80).rotate({ x:1, y:2, z:3, angle: this.angle }) .margin(80).rotate({ x:1, y:2, z:3, angle: this.angle })
.gesture( .gesture(
RotationGesture() RotationGesture()
.onActionStart((event: RotationGestureEvent) => { .onActionStart((event: GestureEvent) => {
console.log('Rotation start') console.log('Rotation start')
}) })
.onActionUpdate((event: RotationGestureEvent) => { .onActionUpdate((event: GestureEvent) => {
this.angle = event.angle this.angle = event.angle
}) })
.onActionEnd(() => { .onActionEnd(() => {
......
...@@ -15,33 +15,34 @@ None ...@@ -15,33 +15,34 @@ None
SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: number }) SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: number })
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| fingers | number | No | 1 | Minimum number of fingers to trigger a swipe gesture. The value ranges from 1 to 10. | | fingers | number | No | 1 | Minimum number of fingers to trigger a swipe gesture. The value ranges from 1 to 10. |
| direction | SwipeDirection | No | SwipeDirection.All | Swipe direction. | | direction | SwipeDirection | No | SwipeDirection.All | Swipe direction. |
| speed | number | No | 100 | Minimum speed of the swipe gesture (100 vp/s). | | speed | number | No | 100 | Minimum speed of the swipe gesture (100 vp/s). |
- SwipeDirection enums - SwipeDirection enums
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| All | All directions. | | All | All directions. |
| Horizontal | Horizontal direction. | | Horizontal | Horizontal direction. |
| Vertical | Vertical direction. | | Vertical | Vertical direction. |
## Events ## Events
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| onAction(callback:(event?: SwipeGestureEvent) =&gt; void) | Callback invoked when a swipe gesture is recognized. | | onAction(callback:(event?: GestureEvent) =&gt; void) | Callback invoked when a swipe gesture is recognized. |
- SwipeGestureEvent attributes - GestureEvent attributes related to the swipe gesture
| Name | Type | Description | | Name | Type | Description |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| angle | number | Angle of the swipe gesture. | | angle | number | Angle of the swipe gesture.<br/>>&nbsp;![icon-note.gif](public_sys-resources/icon-note.gif)&nbsp;**NOTE**<br/>>&nbsp;Angle calculation method: After the swipe gesture is identified, 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. 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 | number | Speed of the swipe gesture. | | speed | number | Speed of the swipe gesture. |
![en-us_image_0000001231374559](figures/en-us_image_0000001231374661.png)
## Example ## Example
...@@ -64,7 +65,7 @@ struct SwipeGestureExample { ...@@ -64,7 +65,7 @@ struct SwipeGestureExample {
.rotate({x: 0, y: 0, z: 1, angle: this.rotateAngle}) .rotate({x: 0, y: 0, z: 1, angle: this.rotateAngle})
.gesture( .gesture(
SwipeGesture({fingers: 1, direction:SwipeDirection.Vertical}) SwipeGesture({fingers: 1, direction:SwipeDirection.Vertical})
.onAction((event: SwipeGestureEvent) => { .onAction((event: GestureEvent) => {
this.speed = event.speed this.speed = event.speed
this.rotateAngle = event.angle this.rotateAngle = event.angle
}) })
...@@ -73,4 +74,4 @@ struct SwipeGestureExample { ...@@ -73,4 +74,4 @@ struct SwipeGestureExample {
} }
``` ```
![en-us_image_0000001257138365](figures/en-us_image_0000001257138365.gif) ![en-us_image_0000001231374559](figures/en-us_image_0000001231374559.gif)
...@@ -30,16 +30,16 @@ Canvas(context: CanvasRenderingContext2D) ...@@ -30,16 +30,16 @@ Canvas(context: CanvasRenderingContext2D)
## Attributes ## Attributes
[Universal attributes](ts-universal-attributes-size.md) are supported. [Universal attributes]( ts-universal-attributes-index.md) are supported.
## Events ## Events
In addition to [universal events](ts-universal-events-click.md), the following events are supported. In addition to [universal events](ts-universal-events-index.md), the following events are supported.
| Name | Parameter | Description | | Name | Parameter | Description |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| onReady(callback: () =&gt; void) | None | Triggered when . | | onReady(callback: () =&gt; void) | None | Triggered when . |
## Example ## Example
......
...@@ -12,7 +12,7 @@ None ...@@ -12,7 +12,7 @@ None
## Modules to Import ## Modules to Import
``` ```
import lottie from 'lottie-ohos-ets' import lottie from 'lottie-ohos-ets'
``` ```
...@@ -30,15 +30,15 @@ path: string, container: object, render: string, loop: boolean, autoplay: boolea ...@@ -30,15 +30,15 @@ path: string, container: object, render: string, loop: boolean, autoplay: boolea
Loads an animation. Before calling this method, declare the **Animator('__lottie_ets')** object and check that the canvas layout is complete. This method can be used together with a lifecycle callback of the **Canvas** component, for example, **onAppear()** and **onPageShow()**. Loads an animation. Before calling this method, declare the **Animator('__lottie_ets')** object and check that the canvas layout is complete. This method can be used together with a lifecycle callback of the **Canvas** component, for example, **onAppear()** and **onPageShow()**.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| path | string | Yes | Path of the animation resource file in the HAP file. The resource file must be in JSON format. Example: **path: "common/lottie/data.json"**. | | path | string | Yes | Path of the animation resource file in the HAP file. The resource file must be in JSON format. Example: **path: "common/lottie/data.json"**. |
| container | object | Yes | Canvas drawing context. A **CanvasRenderingContext2D** object must be declared in advance. | | container | object | Yes | Canvas drawing context. A **CanvasRenderingContext2D** object must be declared in advance. |
| render | string | Yes | Rendering type. The value can only be **"canvas"**. | | render | string | Yes | Rendering type. The value can only be **"canvas"**. |
| loop | boolean \| number | No | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends; the default value is **true**. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays. | | loop | boolean \| number | No | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends; the default value is **true**. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays. |
| autoplay | boolean | No | Whether to automatically play the animation. The default value is **true**. | | autoplay | boolean | No | Whether to automatically play the animation. The default value is **true**. |
| name | string | No | Custom animation name. In later versions, the name can be used to reference and control the animation. The default value is null. | | name | string | No | Custom animation name. In later versions, the name can be used to reference and control the animation. The default value is null. |
| initialSegment | [number, number] | No | Start frame and end frame of the animation, respectively. | | initialSegment | [number, number] | No | Start frame and end frame of the animation, respectively. |
## lottie.destroy ## lottie.destroy
...@@ -48,12 +48,12 @@ destroy(name: string): void ...@@ -48,12 +48,12 @@ destroy(name: string): void
Destroys the animation. This method must be called when a page exits. This method can be used together with a lifecycle callback of the **Canvas** component, for example, **onDisappear()** and **onPageHide()**. Destroys the animation. This method must be called when a page exits. This method can be used together with a lifecycle callback of the **Canvas** component, for example, **onDisappear()** and **onPageHide()**.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | Yes | Name of the animation to destroy, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are destroyed. | | name | string | Yes | Name of the animation to destroy, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are destroyed. |
- Example - Example
``` ```
import lottie from 'lottie-web' import lottie from 'lottie-web'
...@@ -128,12 +128,12 @@ play(name: string): void ...@@ -128,12 +128,12 @@ play(name: string): void
Plays a specified animation. Plays a specified animation.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | Yes | Name of the animation to play, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are played. | | name | string | Yes | Name of the animation to play, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are played. |
- Example - Example
``` ```
lottie.play(this.animateName) lottie.play(this.animateName)
``` ```
...@@ -146,12 +146,12 @@ pause(name: string): void ...@@ -146,12 +146,12 @@ pause(name: string): void
Pauses a specified animation. The next time **lottie.play()** is called, the animation starts from the current frame. Pauses a specified animation. The next time **lottie.play()** is called, the animation starts from the current frame.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | Yes | Name of the animation to pause, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused. | | name | string | Yes | Name of the animation to pause, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused. |
- Example - Example
``` ```
lottie.pause(this.animateName) lottie.pause(this.animateName)
``` ```
...@@ -164,12 +164,12 @@ togglePause(name: string): void ...@@ -164,12 +164,12 @@ togglePause(name: string): void
Pauses or plays a specified animation. This method is equivalent to the switching between **lottie.play()** and **lottie.pause()**. Pauses or plays a specified animation. This method is equivalent to the switching between **lottie.play()** and **lottie.pause()**.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused. | | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused. |
- Example - Example
``` ```
lottie.togglePause(this.animateName) lottie.togglePause(this.animateName)
``` ```
...@@ -182,12 +182,12 @@ stop(name: string): void ...@@ -182,12 +182,12 @@ stop(name: string): void
Stops the specified animation. The next time **lottie.play()** is called, the animation starts from the first frame. Stops the specified animation. The next time **lottie.play()** is called, the animation starts from the first frame.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused. | | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused. |
- Example - Example
``` ```
lottie.stop(this.animateName) lottie.stop(this.animateName)
``` ```
...@@ -200,13 +200,13 @@ setSpeed(speed: number, name: string): void ...@@ -200,13 +200,13 @@ setSpeed(speed: number, name: string): void
Sets the playback speed of the specified animation. Sets the playback speed of the specified animation.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is 0, the animation is paused. If the value is 1.0 or -1.0, the animation plays at the normal speed. | | speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is 0, the animation is paused. If the value is 1.0 or -1.0, the animation plays at the normal speed. |
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are stopped. | | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are stopped. |
- Example - Example
``` ```
lottie.setSpeed(5, this.animateName) lottie.setSpeed(5, this.animateName)
``` ```
...@@ -219,13 +219,13 @@ setDirection(direction: AnimationDirection, name: string): void ...@@ -219,13 +219,13 @@ setDirection(direction: AnimationDirection, name: string): void
Sets the direction in which the specified animation plays. Sets the direction in which the specified animation plays.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.<br/>**AnimationDirection**: 1 \| -1. | | direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.<br/>**AnimationDirection**: 1 \| -1. |
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are set. | | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are set. |
- Example - Example
``` ```
lottie.setDirection(-1, this.animateName) lottie.setDirection(-1, this.animateName)
``` ```
...@@ -235,28 +235,28 @@ Sets the direction in which the specified animation plays. ...@@ -235,28 +235,28 @@ Sets the direction in which the specified animation plays.
Defines an **AnimationItem** object, which is returned by the **loadAnimation** interface and has attributes and interfaces. The attributes are described as follows: Defines an **AnimationItem** object, which is returned by the **loadAnimation** interface and has attributes and interfaces. The attributes are described as follows:
| Name | Type | Description | | Name | Type | Description |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| name | string | Animation name. | | name | string | Animation name. |
| isLoaded | boolean | Whether the animation is loaded. | | isLoaded | boolean | Whether the animation is loaded. |
| currentFrame | number | Frame that is being played. The default precision is a floating-point number greater than or equal to 0.0. After **setSubframe(false)** is called, the value is a positive integer without decimal points. | | currentFrame | number | Frame that is being played. The default precision is a floating-point number greater than or equal to 0.0. After **setSubframe(false)** is called, the value is a positive integer without decimal points. |
| currentRawFrame | number | Number of frames that are being played. The precision is a floating point number greater than or equal to 0.0. | | currentRawFrame | number | Number of frames that are being played. The precision is a floating point number greater than or equal to 0.0. |
| firstFrame | number | First frame of the animation segment that is being played. | | firstFrame | number | First frame of the animation segment that is being played. |
| totalFrames | number | Total number of frames in the animation segment that is being played. | | totalFrames | number | Total number of frames in the animation segment that is being played. |
| frameRate | number | Frame rate (frame/s). | | frameRate | number | Frame rate (frame/s). |
| frameMult | number | Frame rate (frame/ms). | | frameMult | number | Frame rate (frame/ms). |
| playSpeed | number | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is 0, the animation is paused. If the value is **1.0** or **-1.0**, the animation plays at the normal speed. | | playSpeed | number | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is 0, the animation is paused. If the value is **1.0** or **-1.0**, the animation plays at the normal speed. |
| playDirection | number | Playback direction. The options are **1** (forward) and **-1** (backward). | | playDirection | number | Playback direction. The options are **1** (forward) and **-1** (backward). |
| playCount | number | Number of times the animation plays. | | playCount | number | Number of times the animation plays. |
| isPaused | boolean | Whether the current animation is paused. The value **true** means that the animation is paused. | | isPaused | boolean | Whether the current animation is paused. The value **true** means that the animation is paused. |
| autoplay | boolean | Whether to automatically play the animation upon completion of the loading. The value **false** means that the **play()** interface needs to be called to start playing. | | autoplay | boolean | Whether to automatically play the animation upon completion of the loading. The value **false** means that the **play()** interface needs to be called to start playing. |
| loop | boolean \| number | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays. | | loop | boolean \| number | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays. |
| renderer | any | Animation rendering object, which depends on the rendering type. | | renderer | any | Animation rendering object, which depends on the rendering type. |
| animationID | string | Animation ID. | | animationID | string | Animation ID. |
| timeCompleted | number | Number of frames that are played for an animation sequence. The value is affected by the setting of **AnimationSegment** and is the same as the value of **totalFrames**. | | timeCompleted | number | Number of frames that are played for an animation sequence. The value is affected by the setting of **AnimationSegment** and is the same as the value of **totalFrames**. |
| segmentPos | number | ID of the current animation segment. The value is a positive integer greater than or equal to 0. | | segmentPos | number | ID of the current animation segment. The value is a positive integer greater than or equal to 0. |
| isSubframeEnabled | boolean | Whether the precision of **currentFrame** is a floating point number. | | isSubframeEnabled | boolean | Whether the precision of **currentFrame** is a floating point number. |
| segments | AnimationSegment \| AnimationSegment[] | Current segment of the animation. | | segments | AnimationSegment \| AnimationSegment[] | Current segment of the animation. |
## AnimationItem.play ## AnimationItem.play
...@@ -266,12 +266,12 @@ play(name?: string): void ...@@ -266,12 +266,12 @@ play(name?: string): void
Plays an animation. Plays an animation.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | No | Name of the target animation. By default, the value is null. | | name | string | No | Name of the target animation. By default, the value is null. |
- Example - Example
``` ```
this.animateItem.play() this.animateItem.play()
``` ```
...@@ -284,12 +284,12 @@ destroy(name?: string): void ...@@ -284,12 +284,12 @@ destroy(name?: string): void
Destroys an animation. Destroys an animation.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | No | Name of the target animation. By default, the value is null. | | name | string | No | Name of the target animation. By default, the value is null. |
- Example - Example
``` ```
this.animateItem.destroy() this.animateItem.destroy()
``` ```
...@@ -302,12 +302,12 @@ pause(name?: string): void ...@@ -302,12 +302,12 @@ pause(name?: string): void
Pauses an animation. When the **play** interface is called next time, the animation is played from the current frame. Pauses an animation. When the **play** interface is called next time, the animation is played from the current frame.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | No | Name of the target animation. By default, the value is null. | | name | string | No | Name of the target animation. By default, the value is null. |
- Example - Example
``` ```
this.animateItem.pause() this.animateItem.pause()
``` ```
...@@ -320,12 +320,12 @@ togglePause(name?: string): void ...@@ -320,12 +320,12 @@ togglePause(name?: string): void
Pauses or plays an animation. This method is equivalent to the switching between **play** and **pause**. Pauses or plays an animation. This method is equivalent to the switching between **play** and **pause**.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | No | Name of the target animation. By default, the value is null. | | name | string | No | Name of the target animation. By default, the value is null. |
- Example - Example
``` ```
this.animateItem.togglePause() this.animateItem.togglePause()
``` ```
...@@ -338,12 +338,12 @@ stop(name?: string): void ...@@ -338,12 +338,12 @@ stop(name?: string): void
Stops an animation. When the **play** interface is called next time, the animation is played from the first frame. Stops an animation. When the **play** interface is called next time, the animation is played from the first frame.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | No | Name of the target animation. By default, the value is null. | | name | string | No | Name of the target animation. By default, the value is null. |
- Example - Example
``` ```
this.animateItem.stop() this.animateItem.stop()
``` ```
...@@ -356,12 +356,12 @@ setSpeed(speed: number): void ...@@ -356,12 +356,12 @@ setSpeed(speed: number): void
Sets the playback speed of an animation. Sets the playback speed of an animation.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is 0, the animation is paused. If the value is **1.0** or **-1.0**, the animation plays at the normal speed. | | speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is 0, the animation is paused. If the value is **1.0** or **-1.0**, the animation plays at the normal speed. |
- Example - Example
``` ```
this.animateItem.setSpeed(5); this.animateItem.setSpeed(5);
``` ```
...@@ -374,12 +374,12 @@ setDirection(direction: AnimationDirection): void ...@@ -374,12 +374,12 @@ setDirection(direction: AnimationDirection): void
Sets the playback direction of an animation. Sets the playback direction of an animation.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.<br/>**AnimationDirection**: 1 \| -1. | | direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.<br/>**AnimationDirection**: 1 \| -1. |
- Example - Example
``` ```
this.animateItem.setDirection(-1) this.animateItem.setDirection(-1)
``` ```
...@@ -387,19 +387,19 @@ Sets the playback direction of an animation. ...@@ -387,19 +387,19 @@ Sets the playback direction of an animation.
## AnimationItem.goToAndStop ## AnimationItem.goToAndStop
goToAndStop(value: number, isFrame: boolean): void goToAndStop(value: number, isFrame?: boolean): void
Sets the animation to stop at the specified frame or time. Sets the animation to stop at the specified frame or time.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will stop. | | value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will stop. |
| isFrame | boolean | No | Whether to set the animation to stop at the specified frame. The value **true** means to set the animation to stop at the specified frame, and **false** means to set the animation to stop at the specified time progress. The default value is **false**. | | isFrame | boolean | No | Whether to set the animation to stop at the specified frame. The value **true** means to set the animation to stop at the specified frame, and **false** means to set the animation to stop at the specified time progress. The default value is **false**. |
| name | string | No | Name of the target animation. By default, the value is null. | | name | string | No | Name of the target animation. By default, the value is null. |
- Example - Example
``` ```
// Set the animation to stop at the specified frame. // Set the animation to stop at the specified frame.
this.animateItem.goToAndStop(25, true) this.animateItem.goToAndStop(25, true)
...@@ -410,19 +410,19 @@ Sets the animation to stop at the specified frame or time. ...@@ -410,19 +410,19 @@ Sets the animation to stop at the specified frame or time.
## AnimationItem.goToAndPlay ## AnimationItem.goToAndPlay
goToAndPlay(value: number, isFrame: boolean): void goToAndPlay( value: number, isFrame: boolean, name?: string): void
Sets the animation to start from the specified frame or time progress. Sets the animation to start from the specified frame or time progress.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will start. | | value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will start. |
| isFrame | boolean | Yes | Whether to set the animation to start from the specified frame. The value **true** means to set the animation to start from the specified frame, and **false** means to set the animation to start from the specified time progress. The default value is **false**. | | isFrame | boolean | Yes | Whether to set the animation to start from the specified frame. The value **true** means to set the animation to start from the specified frame, and **false** means to set the animation to start from the specified time progress. The default value is **false**. |
| name | string | No | Name of the target animation. By default, the value is null. | | name | string | No | Name of the target animation. By default, the value is null. |
- Example - Example
``` ```
// Set the animation to stop at the specified frame. // Set the animation to stop at the specified frame.
this.animateItem.goToAndPlay(25, true) this.animateItem.goToAndPlay(25, true)
...@@ -438,13 +438,13 @@ playSegments(segments: AnimationSegment | AnimationSegment[], forceFlag: boolean ...@@ -438,13 +438,13 @@ playSegments(segments: AnimationSegment | AnimationSegment[], forceFlag: boolean
Sets the animation to play only the specified segment. Sets the animation to play only the specified segment.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| segments | AnimationSegment = [number, number] \| AnimationSegment[] | Yes | Segment or segment list.<br/>If all segments in the segment list are played, only the last segment is played in the next cycle. | | segments | AnimationSegment = [number, number] \| AnimationSegment[] | Yes | Segment or segment list.<br/>If all segments in the segment list are played, only the last segment is played in the next cycle. |
| forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed. | | forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed. |
- Example - Example
``` ```
// Set the animation to play the specified segment. // Set the animation to play the specified segment.
this.animateItem.playSegments([10, 20], false) this.animateItem.playSegments([10, 20], false)
...@@ -460,12 +460,12 @@ resetSegments(forceFlag: boolean): void ...@@ -460,12 +460,12 @@ resetSegments(forceFlag: boolean): void
Resets the settings configured by the **playSegments** method to play all the frames. Resets the settings configured by the **playSegments** method to play all the frames.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed. | | forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed. |
- Example - Example
``` ```
this.animateItem.resetSegments(true) this.animateItem.resetSegments(true)
``` ```
...@@ -478,7 +478,7 @@ resize(): void ...@@ -478,7 +478,7 @@ resize(): void
Resizes the animation layout. Resizes the animation layout.
- Example - Example
``` ```
this.animateItem.resize() this.animateItem.resize()
``` ```
...@@ -491,12 +491,12 @@ setSubframe(useSubFrame: boolean): void ...@@ -491,12 +491,12 @@ setSubframe(useSubFrame: boolean): void
Sets the precision of the **currentFrame** attribute to display floating-point numbers. Sets the precision of the **currentFrame** attribute to display floating-point numbers.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| useSubFrames | boolean | Yes | Whether the **currentFrame** attribute displays floating-point numbers. By default, the attribute displays floating-point numbers.<br/>**true**: The **currentFrame** attribute displays floating-point numbers.<br/>**false**: The **currentFrame** attribute displays an integer and does not display floating-point numbers. | | useSubFrames | boolean | Yes | Whether the **currentFrame** attribute displays floating-point numbers. By default, the attribute displays floating-point numbers.<br/>**true**: The **currentFrame** attribute displays floating-point numbers.<br/>**false**: The **currentFrame** attribute displays an integer and does not display floating-point numbers. |
- Example - Example
``` ```
this.animateItem.setSubframe(false) this.animateItem.setSubframe(false)
``` ```
...@@ -509,12 +509,12 @@ getDuration(inFrames?: boolean): void ...@@ -509,12 +509,12 @@ getDuration(inFrames?: boolean): void
Obtains the duration (irrelevant to the playback speed) or number of frames for playing an animation sequence. The settings are related to the input parameter **initialSegment** of the **Lottie.loadAnimation** interface. Obtains the duration (irrelevant to the playback speed) or number of frames for playing an animation sequence. The settings are related to the input parameter **initialSegment** of the **Lottie.loadAnimation** interface.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| inFrames | boolean | No | Whether to obtain the duration or number of frames. **true**: number of frames. **false**: duration, in ms. The default value is **false**. | | inFrames | boolean | No | Whether to obtain the duration or number of frames. **true**: number of frames. **false**: duration, in ms. The default value is **false**. |
- Example - Example
``` ```
this.animateItem.getDuration(true) this.animateItem.getDuration(true)
``` ```
...@@ -527,13 +527,13 @@ addEventListener&lt;T = any&gt;(name: AnimationEventName, callback: AnimationEve ...@@ -527,13 +527,13 @@ addEventListener&lt;T = any&gt;(name: AnimationEventName, callback: AnimationEve
Adds an event listener. After the event is complete, the specified callback function is triggered. This method returns the function object that can delete the event listener. Adds an event listener. After the event is complete, the specified callback function is triggered. This method returns the function object that can delete the event listener.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | AnimationEventName | Yes | Animation event type. The available options are as follows:<br/>'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images' | | name | AnimationEventName | Yes | Animation event type. The available options are as follows:<br/>'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images' |
| callback | AnimationEventCallback&lt;T&gt; | Yes | Custom callback. | | callback | AnimationEventCallback&lt;T&gt; | Yes | Custom callback. |
- Example - Example
``` ```
private callbackItem: any = function() { private callbackItem: any = function() {
console.log("grunt loopComplete") console.log("grunt loopComplete")
...@@ -552,13 +552,13 @@ removeEventListener&lt;T = any&gt;(name: AnimationEventName, callback?: Animatio ...@@ -552,13 +552,13 @@ removeEventListener&lt;T = any&gt;(name: AnimationEventName, callback?: Animatio
Removes an event listener. Removes an event listener.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | AnimationEventName | Yes | Animation event type. The available options are as follows:<br/>'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images' | | name | AnimationEventName | Yes | Animation event type. The available options are as follows:<br/>'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images' |
| callback | AnimationEventCallback&lt;T&gt; | Yes | Custom callback. By default, the value is null, meaning that all callbacks of the event will be removed. | | callback | AnimationEventCallback&lt;T&gt; | Yes | Custom callback. By default, the value is null, meaning that all callbacks of the event will be removed. |
- Example - Example
``` ```
this.animateItem.removeEventListener('loopComplete', this.animateName) this.animateItem.removeEventListener('loopComplete', this.animateName)
``` ```
...@@ -571,13 +571,13 @@ triggerEvent&lt;T = any&gt;(name: AnimationEventName, args: T): void ...@@ -571,13 +571,13 @@ triggerEvent&lt;T = any&gt;(name: AnimationEventName, args: T): void
Directly triggers all configured callbacks of a specified event. Directly triggers all configured callbacks of a specified event.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | AnimationEventName | Yes | Animation event type. | | name | AnimationEventName | Yes | Animation event type. |
| args | any | Yes | Custom callback parameters. | | args | any | Yes | Custom callback parameters. |
- Example - Example
``` ```
private triggerCallBack: any = function(item) { private triggerCallBack: any = function(item) {
console.log("trigger loopComplete, name:" + item.name) console.log("trigger loopComplete, name:" + item.name)
......
...@@ -15,12 +15,12 @@ addPath(path: Object): void ...@@ -15,12 +15,12 @@ addPath(path: Object): void
Adds a path to this path. Adds a path to this path.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| path | Object | Yes | null | Path to be added to this path. | | path | Object | Yes | null | Path to be added to this path. |
- Example - Example
``` ```
@Entry @Entry
@Component @Component
...@@ -58,7 +58,7 @@ closePath(): void ...@@ -58,7 +58,7 @@ closePath(): void
Moves the current point of the path back to the start point of the path, and draws a straight line between the current point and the start point. If the shape has already been closed or has only one point, this method does nothing. Moves the current point of the path back to the start point of the path, and draws a straight line between the current point and the start point. If the shape has already been closed or has only one point, this method does nothing.
- Example - Example
``` ```
@Entry @Entry
@Component @Component
...@@ -97,13 +97,13 @@ moveTo(x: number, y: number): void ...@@ -97,13 +97,13 @@ moveTo(x: number, y: number): void
Moves the current coordinate point of the path to the target point, without drawing a line during the movement. Moves the current coordinate point of the path to the target point, without drawing a line during the movement.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| x | number | Yes | 0 | X-coordinate of the target point. | | x | number | Yes | 0 | X-coordinate of the target point. |
| y | number | Yes | 0 | Y-coordinate of the target point. | | y | number | Yes | 0 | Y-coordinate of the target point. |
- Example - Example
``` ```
@Entry @Entry
@Component @Component
...@@ -142,13 +142,13 @@ lineTo(x: number, y: number): void ...@@ -142,13 +142,13 @@ lineTo(x: number, y: number): void
Draws a straight line from the current point to the target point. Draws a straight line from the current point to the target point.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| x | number | Yes | 0 | X-coordinate of the target point. | | x | number | Yes | 0 | X-coordinate of the target point. |
| y | number | Yes | 0 | Y-coordinate of the target point. | | y | number | Yes | 0 | Y-coordinate of the target point. |
- Example - Example
``` ```
@Entry @Entry
@Component @Component
...@@ -188,17 +188,17 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, ...@@ -188,17 +188,17 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number,
Draws a cubic bezier curve on the canvas. Draws a cubic bezier curve on the canvas.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| cp1x | number | Yes | 0 | X-coordinate of the first parameter of the bezier curve. | | cp1x | number | Yes | 0 | X-coordinate of the first parameter of the bezier curve. |
| cp1y | number | Yes | 0 | Y-coordinate of the first parameter of the bezier curve. | | cp1y | number | Yes | 0 | Y-coordinate of the first parameter of the bezier curve. |
| cp2x | number | Yes | 0 | X-coordinate of the second parameter of the bezier curve. | | cp2x | number | Yes | 0 | X-coordinate of the second parameter of the bezier curve. |
| cp2y | number | Yes | 0 | Y-coordinate of the second parameter of the bezier curve. | | cp2y | number | Yes | 0 | Y-coordinate of the second parameter of the bezier curve. |
| x | number | Yes | 0 | X-coordinate of the end point on the bezier curve. | | x | number | Yes | 0 | X-coordinate of the end point on the bezier curve. |
| y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve. | | y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve. |
- Example - Example
``` ```
@Entry @Entry
@Component @Component
...@@ -234,15 +234,15 @@ quadraticCurveTo(cpx: number, cpy: number, x: number ,y: number): void ...@@ -234,15 +234,15 @@ quadraticCurveTo(cpx: number, cpy: number, x: number ,y: number): void
Draws a quadratic curve on the canvas. Draws a quadratic curve on the canvas.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| cpx | number | Yes | 0 | X-coordinate of the bezier curve parameter. | | cpx | number | Yes | 0 | X-coordinate of the bezier curve parameter. |
| cpy | number | Yes | 0 | Y-coordinate of the bezier curve parameter. | | cpy | number | Yes | 0 | Y-coordinate of the bezier curve parameter. |
| x | number | Yes | 0 | X-coordinate of the end point on the bezier curve. | | x | number | Yes | 0 | X-coordinate of the end point on the bezier curve. |
| y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve. | | y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve. |
- Example - Example
``` ```
@Entry @Entry
@Component @Component
...@@ -274,22 +274,22 @@ Draws a quadratic curve on the canvas. ...@@ -274,22 +274,22 @@ Draws a quadratic curve on the canvas.
## arc ## arc
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: number): void arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void
Draws an arc on the canvas. Draws an arc on the canvas.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| x | number | Yes | 0 | X-coordinate of the center point of the arc. | | x | number | Yes | 0 | X-coordinate of the center point of the arc. |
| y | number | Yes | 0 | Y-coordinate of the center point of the arc. | | y | number | Yes | 0 | Y-coordinate of the center point of the arc. |
| radius | number | Yes | 0 | Radius of the arc. | | radius | number | Yes | 0 | Radius of the arc. |
| startAngle | number | Yes | 0 | Start radian of the arc. | | startAngle | number | Yes | 0 | Start radian of the arc. |
| endAngle | number | Yes | 0 | End radian of the arc. | | endAngle | number | Yes | 0 | End radian of the arc. |
| anticlockwise | boolean | No | false | Whether to draw the arc counterclockwise. | | anticlockwise | boolean | No | false | Whether to draw the arc counterclockwise. |
- Example - Example
``` ```
@Entry @Entry
@Component @Component
...@@ -324,16 +324,16 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void ...@@ -324,16 +324,16 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
Draws an arc based on the radius and points on the arc. Draws an arc based on the radius and points on the arc.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| x1 | number | Yes | 0 | X-coordinate of the first point on the arc. | | x1 | number | Yes | 0 | X-coordinate of the first point on the arc. |
| y1 | number | Yes | 0 | Y-coordinate of the first point on the arc. | | y1 | number | Yes | 0 | Y-coordinate of the first point on the arc. |
| x2 | number | Yes | 0 | X-coordinate of the second point on the arc. | | x2 | number | Yes | 0 | X-coordinate of the second point on the arc. |
| y2 | number | Yes | 0 | Y-coordinate of the second point on the arc. | | y2 | number | Yes | 0 | Y-coordinate of the second point on the arc. |
| radius | number | Yes | 0 | Radius of the arc. | | radius | number | Yes | 0 | Radius of the arc. |
- Example - Example
``` ```
@Entry @Entry
@Component @Component
...@@ -369,19 +369,19 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number ...@@ -369,19 +369,19 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number
Draws an ellipse in the specified rectangular region. Draws an ellipse in the specified rectangular region.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| x | number | Yes | 0 | X-coordinate of the ellipse center. | | x | number | Yes | 0 | X-coordinate of the ellipse center. |
| y | number | Yes | 0 | Y-coordinate of the ellipse center. | | y | number | Yes | 0 | Y-coordinate of the ellipse center. |
| radiusX | number | Yes | 0 | Ellipse radius on the x-axis. | | radiusX | number | Yes | 0 | Ellipse radius on the x-axis. |
| radiusY | number | Yes | 0 | Ellipse radius on the y-axis. | | radiusY | number | Yes | 0 | Ellipse radius on the y-axis. |
| rotation | number | Yes | 0 | Rotation angle of the ellipse, in radians. | | rotation | number | Yes | 0 | Rotation angle of the ellipse, in radians. |
| startAngle | number | Yes | 0 | Angle of the start point for drawing the ellipse, in radians. | | startAngle | number | Yes | 0 | Angle of the start point for drawing the ellipse, in radians. |
| endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse, in radians. | | endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse, in radians. |
| anticlockwise | number | No | 0 | Whether to draw the ellipse in the counterclockwise direction. The value **0** means to draw the ellipse in the clockwise direction, and **1** means to draw the ellipse in the counterclockwise direction. This parameter is optional. The default value is **0**. | | anticlockwise | number | No | 0 | Whether to draw the ellipse in the counterclockwise direction. The value **0** means to draw the ellipse in the clockwise direction, and **1** means to draw the ellipse in the counterclockwise direction. This parameter is optional. The default value is **0**. |
- Example - Example
``` ```
@Entry @Entry
@Component @Component
...@@ -417,15 +417,15 @@ rect(x: number, y: number, width: number, height: number): void ...@@ -417,15 +417,15 @@ rect(x: number, y: number, width: number, height: number): void
Creates a rectangle. Creates a rectangle.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle. | | x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle. |
| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle. | | y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle. |
| width | number | Yes | 0 | Width of the rectangle. | | width | number | Yes | 0 | Width of the rectangle. |
| height | number | Yes | 0 | Height of the rectangle. | | height | number | Yes | 0 | Height of the rectangle. |
- Example - Example
``` ```
@Entry @Entry
@Component @Component
......
...@@ -23,46 +23,47 @@ None ...@@ -23,46 +23,47 @@ None
AlphabetIndexer(value: {arrayValue : Array&lt;string&gt;, selected : number}) AlphabetIndexer(value: {arrayValue : Array&lt;string&gt;, selected : number})
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| arrayValue | Array&lt;string&gt; | Yes | - | Array of strings to be displayed in the alphabetic index bar. | | arrayValue | Array&lt;string&gt; | Yes | - | Array of strings to be displayed in the alphabetic index bar. |
| selected | number | Yes | - | ID of a selected item. | | selected | number | Yes | - | ID of a selected item. |
## Attributes ## Attributes
| Name | Type | Description | | Name | Type | Description |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| selectedColor | Color | Font color of the selected text. | | selectedColor | Color | Font color of the selected text. |
| popupColor | Color | Font color of the pop-up text. | | popupColor | Color | Font color of the pop-up text. |
| selectedBackgroundColor | Color | Background color of the selected text. | | selectedBackgroundColor | Color | Background color of the selected text. |
| popupBackground | Color | Background color of the pop-up text. | | popupBackground | Color | Background color of the pop-up text. |
| usingPopup | boolean | Whether to use pop-up text. | | usingPopup | boolean | Whether to use pop-up text. |
| selectedFont | {<br/>size?: number,<br/>weight?: FontWeight,<br/>family?: string,<br/>style?: FontStyle<br/>} | Font style of the selected text. | | selectedFont | {<br/>size?: number,<br/>weight?: FontWeight,<br/>family?: string,<br/>style?: FontStyle<br/>} | Font style of the selected text. |
| popupFont | {<br/>size?: number,<br/>weight?: FontWeight,<br/>family?: string,<br/>style?: FontStyle<br/>} | Font style of the pop-up text. | | popupFont | {<br/>size?: number,<br/>weight?: FontWeight,<br/>family?: string,<br/>style?: FontStyle<br/>} | Font style of the pop-up text. |
| font | {<br/>size?: number,<br/>weight?: FontWeight,<br/>family?: string,<br/>style?: FontStyle<br/>} | Default font style of the alphabetic index bar. | | font | {<br/>size?: number,<br/>weight?: FontWeight,<br/>family?: string,<br/>style?: FontStyle<br/>} | Default font style of the alphabetic index bar. |
| itemSize | Length | Size of an item in the alphabetic index bar. The item is a square, and the side length needs to be set. | | itemSize | Length | Size of an item in the alphabetic index bar. The item is a square, and the side length needs to be set. |
| alignStyle | IndexerAlign | Alignment style of the alphabetic index bar. Left alignment and right alignment are supported. The alignment style affects the position of the pop-up window. | | alignStyle | IndexerAlign | Alignment style of the alphabetic index bar. Left alignment and right alignment are supported. The alignment style affects the position of the pop-up window. |
- IndexerAlign enums - IndexerAlign enums
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| Left | The pop-up window is displayed on the right of the alphabetic indexer bar. | | Left | The pop-up window is displayed on the right of the alphabetic indexer bar. |
| Right | The pop-up window is displayed on the left of the alphabetic indexer bar. | | Right | The pop-up window is displayed on the left of the alphabetic indexer bar. |
## Events ## Events
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| onSelected(index: number) =&gt; void | Callback invoked when an item in the alphabetic indexer bar is selected. | | onSelected(index:&nbsp;number)&nbsp;=&gt;&nbsp;void<sup>(deprecated) </sup> | Invoked when an item in the alphabetic indexer bar is selected. |
| onRequestPopupData(callback: (index: number) =&gt; Array&lt;string&gt;)<sup>8+</sup> | Invoked when a request for displaying content in the index prompt window is sent when an item in the alphabetic indexer bar is selected.<br/>The return value is a string array corresponding to the indexes. The string array is displayed vertically in the pop-up window. It can display up to five strings at a time and allows scrolling. | | onSelect(index:&nbsp;number)&nbsp;=&gt;&nbsp;void<sup>8+</sup> | Invoked when an item in the alphabetic indexer bar is selected. |
| onPopupSelected(callback: (index: number) =&gt; void)<sup>8+</sup> | Invoked when an item in the index pop-up window is selected. | | onRequestPopupData(callback: (index: number) =&gt; Array&lt;string&gt;)<sup>8+</sup> | Invoked when a request for displaying content in the index prompt window is sent when an item in the alphabetic indexer bar is selected.<br/>The return value is a string array corresponding to the indexes. The string array is displayed vertically in the pop-up window. It can display up to five strings at a time and allows scrolling. |
| onPopupSelect(callback: (index: number) =&gt; void)<sup>8+</sup> | Invoked when an item in the index pop-up window is selected. |
## Example ## Example
``` ```
@Entry @Entry
@Component @Component
...@@ -80,7 +81,7 @@ struct AlphabetIndexerSample { ...@@ -80,7 +81,7 @@ struct AlphabetIndexerSample {
.popupFont({ size: 30, weight: FontWeight.Bolder }) // Font style of the pop-up text .popupFont({ size: 30, weight: FontWeight.Bolder }) // Font style of the pop-up text
.itemSize(28) // Size of each item (square) .itemSize(28) // Size of each item (square)
.alignStyle(IndexerAlign.Left) // Left aligned .alignStyle(IndexerAlign.Left) // Left aligned
.onSelected((index: number) => { .onSelect((index: number) => {
console.info(this.value[index] + 'Selected') // Event indicating that an item is selected console.info(this.value[index] + 'Selected') // Event indicating that an item is selected
}) })
.margin({ left: 50 }) .margin({ left: 50 })
......
...@@ -25,9 +25,9 @@ RowSplit() ...@@ -25,9 +25,9 @@ RowSplit()
## Attributes ## Attributes
| Name | Type | Description | | Name | Type | Description |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| resizeable | boolean | Whether the divider can be dragged. The default value is **false**. | | resizeable | boolean | Whether the divider can be dragged. The default value is **false**. |
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> Similar to **&lt;RowSplit&gt;**, the divider of **&lt;RowSplit&gt;** can be dragged to a position that just fully holds a component. > Similar to **&lt;RowSplit&gt;**, the divider of **&lt;RowSplit&gt;** can be dragged to a position that just fully holds a component.
...@@ -35,14 +35,14 @@ RowSplit() ...@@ -35,14 +35,14 @@ RowSplit()
## Example ## Example
``` ```
@Entry @Entry
@Component @Component
struct RowSplitExample { struct RowSplitExample {
build() { build() {
Column() { Column() {
Text('The secant line can be dragged').fontSize(9).fontColor(0xCCCCCC).width('90%') Text('The second line can be dragged').fontSize(9).fontColor(0xCCCCCC).width('90%')
RowSplit() { RowSplit() {
Text('1').width('10%').height(100).backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) Text('1').width('10%').height(100).backgroundColor(0xF5DEB3).textAlign(TextAlign.Center)
Text('2').width('10%').height(100).backgroundColor(0xD2B48C).textAlign(TextAlign.Center) Text('2').width('10%').height(100).backgroundColor(0xD2B48C).textAlign(TextAlign.Center)
......
...@@ -25,19 +25,19 @@ Scroll(scroller?: Scroller) ...@@ -25,19 +25,19 @@ Scroll(scroller?: Scroller)
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| scrollable | ScrollDirection | ScrollDirection.Vertical | Scroll method. | | scrollable | ScrollDirection | ScrollDirection.Vertical | Scroll method. |
| scrollBar | [BarState](ts-appendix-enums.md#barstate-enums) | Auto | Scroll bar status. | | scrollBar | [BarState](ts-appendix-enums.md#barstate-enums) | Auto | Scroll bar status. |
| scrollBarColor | Color | - | Color of the scroll bar. | | scrollBarColor | Color | - | Color of the scroll bar. |
| scrollBarWidth | Length | - | Width of the scrollbar. | | scrollBarWidth | Length | - | Width of the scrollbar. |
- ScrollDirection - ScrollDirection
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| 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. |
## Scroller ## Scroller
...@@ -62,11 +62,11 @@ Scrolls to the specified position. ...@@ -62,11 +62,11 @@ Scrolls to the specified position.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| xOffset | Length | Yes | - | Horizontal scrolling offset. | | xOffset | Length | Yes | - | Horizontal scrolling offset. |
| yOffset | Length | Yes | - | Vertical scrolling offset. | | yOffset | Length | Yes | - | Vertical scrolling offset. |
| animation | {<br/>duration: number,<br/>curve: Curve \|<br/>CubicBezier \|<br/>SpringCurve<br/>} | No | | Animation configuration, which includes the following:<br/>- **duration**: scrolling duration.<br/>- **curve**: scrolling curve. | | animation | {<br/>duration: number,<br/>curve: Curve \|<br/>CubicBezier \|<br/>SpringCurve<br/>} | No | | Animation configuration, which includes the following:<br/>- **duration**: scrolling duration.<br/>- **curve**: scrolling curve. |
### scroller.scrollEdge ### scroller.scrollEdge
...@@ -78,9 +78,9 @@ Scrolls to the edge of the container. ...@@ -78,9 +78,9 @@ Scrolls to the edge of the container.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| value | Edge | Yes | - | Edge position to scroll to. | | value | Edge | Yes | - | Edge position to scroll to. |
### scroller.scrollPage ### scroller.scrollPage
...@@ -90,7 +90,7 @@ scrollPage(value: { next: boolean, direction?: Axis }): void ...@@ -90,7 +90,7 @@ scrollPage(value: { next: boolean, direction?: Axis }): void
Scrolls to the next or previous page. Scrolls to the next or previous page.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| next | boolean | Yes | - | Whether to turn to the next page. The value **true** means to scroll to the next page, and the value **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 the value **false** means to scroll to the previous page. |
...@@ -104,9 +104,9 @@ Obtains the scrolling offset. ...@@ -104,9 +104,9 @@ Obtains the scrolling offset.
- Return values - Return values
| Type | Description | | Type | Description |
| -------- | -------- | | -------- | -------- |
| {<br/>xOffset: number,<br/>yOffset: number<br/>} | **xOffset**: horizontal scrolling offset.<br/>**yOffset**: vertical scrolling offset. | | {<br/>xOffset: number,<br/>yOffset: number<br/>} | **xOffset**: horizontal scrolling offset.<br/>**yOffset**: vertical scrolling offset. |
### scroller.scrollToIndex ### scroller.scrollToIndex
...@@ -122,18 +122,18 @@ Scrolls to the specified index. ...@@ -122,18 +122,18 @@ Scrolls to the specified index.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| value | number | Yes | - | Index of the item to be scrolled to in the list. | | value | number | Yes | - | Index of the item to be scrolled to in the list. |
## Events ## Events
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| onScroll(xOffset: number, yOffset: number) =&gt; void | Invoked to return the horizontal and vertical offsets during scrolling when the specified scroll event occurs. | | onScroll(xOffset: number, yOffset: number) =&gt; void | Invoked to return the horizontal and vertical offsets during scrolling when the specified scroll event occurs. |
| onScrollEdge(side: Edge) =&gt; void | Callback for the event of scrolling to the edge. | | onScrollEdge(side: Edge) =&gt; void | Callback for the event of scrolling to the edge. |
| onScrollEnd() =&gt; void | Invoked when scrolling stops. | | onScrollEnd() =&gt; void | Invoked when scrolling stops. |
## Example ## Example
......
...@@ -36,15 +36,6 @@ Tabs(value: {barPosition?: BarPosition, index?: number, controller?: [TabsContro ...@@ -36,15 +36,6 @@ Tabs(value: {barPosition?: BarPosition, index?: number, controller?: [TabsContro
| End | If the **vertical** attribute is set to **true**, the tab is on the right of the container. If the **vertical** attribute is set to **false**, the tab is at the bottom of the container. | | End | If the **vertical** attribute is set to **true**, the tab is on the right of the container. If the **vertical** attribute is set to **false**, the tab is at the bottom of the container. |
### TabsController
Defines a tab controller, which is used to control switching of tabs.
| API | Description |
| -------- | -------- |
| changeIndex(value: number): void | Changes the index of a tab. The value starts from **0**. |
## Attributes ## Attributes
Touch target configuration is not supported. Touch target configuration is not supported.
...@@ -71,6 +62,27 @@ Touch target configuration is not supported. ...@@ -71,6 +62,27 @@ Touch target configuration is not supported.
| -------- | -------- | | -------- | -------- |
| onChange(callback: (index: number) =&gt; void) | Event triggered when a tab is switched. | | onChange(callback: (index: number) =&gt; void) | Event triggered when a tab is switched. |
## TabsController
Defines a tab controller, which is used to control switching of tabs.
### Objects to Import
```
controller: TabsController = new TabsController()
```
### changeIndex
changeIndex(value: number): void
Switches to the specified tab.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| value | number | Yes | - | Index of a tab. The value starts from **0**. |
## Example ## Example
......
...@@ -4,28 +4,28 @@ ...@@ -4,28 +4,28 @@
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> This animation is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This animation is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| animateTo(value: [AnimationOption](#animationoption-object), event: ()=&gt; void) : void | Provides a transition animation when the status changes due to the closure code.<br/>**event** specifies the closure function that displays the dynamic effect. The system automatically inserts the transition animation if the status changes in the closure function. | | animateTo(value: [AnimationOptions](#animationoptions), event: ()=&gt; void) : void | Provides a transition animation when the status changes due to the closure code.<br/>**event** specifies the closure function that displays the dynamic effect. The system automatically inserts the transition animation if the status changes in the closure function. |
## AnimationOption Object ## AnimationOptions
- Attributes - Attributes
| Name | Type | Default Value | Description | | Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| duration | number | 1000 | Animation duration, in ms. | | duration | number | 1000 | Animation duration, in ms. |
| tempo | number | 1.0 | Animation playback speed. A larger value indicates faster animation playback, and a smaller value indicates slower animation playback. The value **0** means that there is no animation. | | tempo | number | 1.0 | Animation playback speed. A larger value indicates faster animation playback, and a smaller value indicates slower animation playback. The value **0** means that there is no animation. |
| curve | Curve \| Curves | Linear | Animation curve. | | curve | Curve \| Curves | Linear | Animation curve. |
| delay | number | 0 | Delay of animation playback, in ms. By default, the playback is not delayed. | | delay | number | 0 | Delay of animation playback, in ms. By default, the playback is not delayed. |
| iterations | number | 1 | Number of times that the animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times. | | iterations | number | 1 | Number of times that the animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times. |
| playMode | PlayMode | Normal | Animation playback mode. By default, the animation is played from the beginning after the playback is complete. | | playMode | PlayMode | Normal | Animation playback mode. By default, the animation is played from the beginning after the playback is complete. |
- APIs - APIs
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| onFinish() =&gt; void | Callback invoked when the animation playback is complete. | | onFinish() =&gt; void | Callback invoked when the animation playback is complete. |
## Example ## Example
......
...@@ -15,9 +15,9 @@ The **&lt;Video&gt;** component does not support any child component. ...@@ -15,9 +15,9 @@ The **&lt;Video&gt;** component does not support any child component.
## APIs ## APIs
Video(value: VideoOption) Video(value: VideoOptions)
- VideoOption attributes - VideoOptions attributes
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| src | string | No | - | Path of the video source. | | src | string | No | - | Path of the video source. |
...@@ -27,13 +27,13 @@ Video(value: VideoOption) ...@@ -27,13 +27,13 @@ Video(value: VideoOption)
- PlaybackSpeed<sup>8+</sup> - PlaybackSpeed<sup>8+</sup>
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| Speed_Forward_0_75_X | 0.75x playback speed. | | Speed_Forward_0_75_X | 0.75x playback speed. |
| Speed_Forward_1_00_X | 1x playback speed. | | Speed_Forward_1_00_X | 1x playback speed. |
| Speed_Forward_1_25_X | 1.25x playback speed. | | Speed_Forward_1_25_X | 1.25x playback speed. |
| Speed_Forward_1_75_X | 1.75x playback speed. | | Speed_Forward_1_75_X | 1.75x playback speed. |
| Speed_Forward_2_00_X | 2x playback speed. | | Speed_Forward_2_00_X | 2x playback speed. |
## Attributes ## Attributes
...@@ -49,38 +49,94 @@ Video(value: VideoOption) ...@@ -49,38 +49,94 @@ Video(value: VideoOption)
## Events ## Events
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| onStart() =&gt; void | Triggered when the video is played. | | onStart() =&gt; void | Triggered when the video is played. |
| onPause() =&gt; void | Triggered when the video playback is paused. | | onPause() =&gt; void | Triggered when the video playback is paused. |
| onFinish() =&gt; void | Triggered when the video playback is finished. | | onFinish() =&gt; void | Triggered when the video playback is finished. |
| onError() =&gt; void | Triggered when the video playback fails. | | onError() =&gt; void | Triggered when the video playback fails. |
| onPrepared(event?: { duration: number }) =&gt; void | Triggered when video preparation is complete. The video duration (in seconds) is obtained from **duration**. | | onPrepared(event?: { duration: number }) =&gt; void | Triggered when video preparation is complete. The video duration (in seconds) is obtained from **duration**. |
| onSeeking(event?: { time: number }) =&gt; void | Triggered to report the time (in seconds) when the progress bar is being dragged. | | onSeeking(event?: { time: number }) =&gt; void | Triggered to report the time (in seconds) when the progress bar is being dragged. |
| onSeeked(event?: { time: number }) =&gt; void | Triggered to report the playback time (in seconds) when the user finishes dragging the progress bar. | | onSeeked(event?: { time: number }) =&gt; void | Triggered to report the playback time (in seconds) when the user finishes dragging the progress bar. |
| onUpdate(event?: { time: number }) =&gt; void | Triggered once per 250 ms when the playback progress changes. The unit of the current playback time is second. | | onUpdate(event?: { time: number }) =&gt; void | Triggered once per 250 ms when the playback progress changes. The unit of the current playback time is second. |
### VideoController ## VideoController
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** A **VideoController** object can control one or more videos.
> A **VideoController** object can control one or more videos.
| Name | Description |
| -------- | -------- | ### Objects to Import
| start() : void | Starts playback. |
| pause() : void | Pauses playback. | ```
| stop() : void | Stops playback. | controller: VideoController = new VideoController();
| setCurrentTime(value: number) | Sets the video playback position. | ```
| setCurrentTime(value: number, seekMode: SeekMode)<sup>8+</sup> | Sets the video playback position with the specified seek mode. |
### start
start(): void
Starts playback.
### pause
pause(): void
Pauses playback.
### stop
stop(): void
Stops playback.
### setCurrentTime
setCurrentTime(value: number)
Sets the video playback position.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| value | number | Yes | - | Video playback position. |
### requestFullscreen
requestFullscreen(value: boolean)
Requests full-screen mode.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| value | number | Yes | false | Whether the playback is in full-screen mode. |
### exitFullscreen
exitFullscreen()
Exits full-screen mode.
### setCurrentTime<sup>8+</sup>
setCurrentTime(value: number, seekMode: SeekMode)
Sets the video playback position with the specified seek mode.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| value | number | Yes | - | Video playback position. |
| seekMode | SeekMode | Yes | - | Seek mode. |
- SeekMode<sup>8+</sup> - SeekMode<sup>8+</sup>
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| PreviousKeyframe | Seeks to the nearest previous keyframe. | | PreviousKeyframe | Seeks to the nearest previous keyframe. |
| NextKeyframe | Seeks to the nearest next keyframe. | | NextKeyframe | Seeks to the nearest next keyframe. |
| ClosestKeyframe | Seeks to the nearest keyframe. | | ClosestKeyframe | Seeks to the nearest keyframe. |
| Accurate | Seeks to a specific frame, regardless of whether the frame is a keyframe. | | Accurate | Seeks to a specific frame, regardless of whether the frame is a keyframe. |
## Example ## Example
......
...@@ -10,7 +10,7 @@ The **CustomDialogController** class is used to display a custom dialog box. ...@@ -10,7 +10,7 @@ The **CustomDialogController** class is used to display a custom dialog box.
## APIs ## APIs
CustomDialogController(value:{builder: CustomDialog, cancel?: () =&gt; void, autoCancel?: boolean}) CustomDialogController(value:{builder: CustomDialog, cancel?: () =&gt; void, autoCancel?: boolean, alignment?: DialogAlignment, offset?: Offset, customStyle?: boolean})
- Parameters - Parameters
......
...@@ -48,7 +48,6 @@ struct DatePickerDialogExample01 { ...@@ -48,7 +48,6 @@ struct DatePickerDialogExample01 {
onAccept: (value: DatePickerResult) => { onAccept: (value: DatePickerResult) => {
this.selectedDate.setFullYear(value.year, value.month, value.day) this.selectedDate.setFullYear(value.year, value.month, value.day)
console.info("DatePickerDialog:onAccept()" + JSON.stringify(value)) console.info("DatePickerDialog:onAccept()" + JSON.stringify(value))
}
}, },
onCancel: () => { onCancel: () => {
console.info("DatePickerDialog:onCancel()") console.info("DatePickerDialog:onCancel()")
...@@ -82,7 +81,6 @@ struct DatePickerDialogExample02 { ...@@ -82,7 +81,6 @@ struct DatePickerDialogExample02 {
onAccept: (value: DatePickerResult) => { onAccept: (value: DatePickerResult) => {
this.selectedDate.setFullYear(value.year, value.month, value.day) this.selectedDate.setFullYear(value.year, value.month, value.day)
console.info("DatePickerDialog:onAccept()" + JSON.stringify(value)) console.info("DatePickerDialog:onAccept()" + JSON.stringify(value))
}
}, },
onCancel: () => { onCancel: () => {
console.info("DatePickerDialog:onCancel()") console.info("DatePickerDialog:onCancel()")
......
...@@ -11,11 +11,11 @@ None ...@@ -11,11 +11,11 @@ None
## TextPickerDialog.show ## TextPickerDialog.show
show(options: TextPickerDialogOption) show(options: TextPickerDialogOptions)
Shows a text picker in the given settings. Shows a text picker in the given settings.
- TextPickerDialogOption parameters - TextPickerDialogOptions
| Name| Type| Mandatory| Default Value| Description| | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| range | string[] | Yes| - | Data selection range of the picker.| | range | string[] | Yes| - | Data selection range of the picker.|
......
...@@ -40,7 +40,6 @@ struct TimePickerDialogExample01 { ...@@ -40,7 +40,6 @@ struct TimePickerDialogExample01 {
TimePickerDialog.show({ TimePickerDialog.show({
useMilitaryTime: this.isUseMilitaryTime, useMilitaryTime: this.isUseMilitaryTime,
onAccept: (value: TimePickerResult) => { onAccept: (value: TimePickerResult) => {
this.selectedDate.setHours(value.hour, value.minute, value.second)
console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)) console.info("TimePickerDialog:onAccept()" + JSON.stringify(value))
}, },
onCancel: () => { onCancel: () => {
...@@ -69,7 +68,6 @@ struct TimePickerDialogExample02 { ...@@ -69,7 +68,6 @@ struct TimePickerDialogExample02 {
TimePickerDialog.show({ TimePickerDialog.show({
useMilitaryTime: this.isUseMilitaryTime, useMilitaryTime: this.isUseMilitaryTime,
onAccept: (value: TimePickerResult) => { onAccept: (value: TimePickerResult) => {
this.selectedDate.setHours(value.hour, value.minute, value.second)
console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)) console.info("TimePickerDialog:onAccept()" + JSON.stringify(value))
}, },
onCancel: () => { onCancel: () => {
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > ![icon-note.gif](public_sys-resources/icon-note.gif) **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 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions ## Required Permissions
...@@ -13,14 +13,14 @@ None ...@@ -13,14 +13,14 @@ None
## Attributes ## Attributes
| **Name** | **Type** | **Default Value** | **Description** | | **Name** | **Type** | **Default Value** | **Description** |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| touchable | boolean | true | Whether the current component is touchable. | | touchable | boolean | true | Whether the current component is touchable. |
## Example ## Example
``` ```
@Entry @Entry
@Component @Component
......
...@@ -12,22 +12,22 @@ None ...@@ -12,22 +12,22 @@ None
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| hoverEffect | HoverEffect | HoverEffect.Auto | Hover effect of the component in hover state. | | hoverEffect | HoverEffect | HoverEffect.Auto | Hover effect of the component in hover state. |
- HoverEffect enums - HoverEffect enums
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| Auto | Default hover effect. | | Auto | Default hover effect. |
| Scale | Scale effect. | | Scale | Scale effect. |
| Board | Fade-in and fade-out effect. | | Highlight | Fade-in and fade-out effect. |
| None | No effect. | | None | No effect. |
## Example ## Example
``` ```
@Entry @Entry
@Component @Component
...@@ -43,17 +43,17 @@ struct HoverExample { ...@@ -43,17 +43,17 @@ struct HoverExample {
.position({ x: 40, y: 120 }) .position({ x: 40, y: 120 })
.hoverEffect(HoverEffect.Scale) .hoverEffect(HoverEffect.Scale)
.onHover((isHover: boolean) => { .onHover((isHover: boolean) => {
console.info('Scale' + isHover) console.info('Scale isHover: ' + isHover)
this.isHoverVal = isHover this.isHoverVal = isHover
}) })
Text('Board').fontSize(20).fontColor(Color.Gray).width('90%').position({ x: 0, y: 380 }) Text('Board').fontSize(20).fontColor(Color.Gray).width('90%').position({ x: 0, y: 380 })
Column() Column()
.width('80%').height(200).backgroundColor(Color.Gray) .width('80%').height(200).backgroundColor(Color.Gray)
.hoverEffect(HoverEffect.Board) .hoverEffect(HoverEffect.Highlight)
.position({ x: 40, y: 420 }) .position({ x: 40, y: 420 })
.onHover((isHover: boolean) => { .onHover((isHover: boolean) => {
console.info('HoverEffect.Board') console.info('Highlight isHover: ' +isHover )
this.isHoverVal = isHover this.isHoverVal = isHover
}) })
} }
......
...@@ -15,21 +15,21 @@ None ...@@ -15,21 +15,21 @@ None
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| stateStyle | StateStyles | - | Sets the styles of a component for different states. | | stateStyles | StateStyles | - | Styles of a component for different states. |
- StateStyles<sup>8+</sup> - StateStyles<sup>8+</sup>
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| normal | ()=&gt;void | No | - | Style of the component when stateless. | | normal | ()=&gt;void | No | - | Style of the component when stateless. |
| pressed | ()=&gt;void | No | - | Style of the component in the pressed state. | | pressed | ()=&gt;void | No | - | Style of the component in the pressed state. |
| disabled | ()=&gt;void | No | - | Style of the component in disabled state. | | disabled | ()=&gt;void | No | - | Style of the component in disabled state. |
## Example ## Example
``` ```
@Entry @Entry
@Component @Component
......
...@@ -13,21 +13,21 @@ None ...@@ -13,21 +13,21 @@ None
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| bindPopup | show: boolean,<br/>popup: PopupOption \| CustomPopupOption | - | Settings of the popup bound to a component.<br/>**show**: whether to display the popup on the creation page by default. The default value is **false**.<br/>**popup**: parameters of the current popup. | | bindPopup | show: boolean,<br/>popup: PopupOptions \| CustomPopupOptions | - | Settings of the popup bound to a component.<br/>**show**: whether to display the popup on the creation page by default. The default value is **false**.<br/>**popup**: parameters of the current popup. |
- PopupOption attributes - PopupOptions attributes
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| message | string | Yes | - | Content of the popup message. | | message | string | Yes | - | Content of the popup message. |
| placementOnTop | boolean | No | false | Whether to display the popup above the component. The default value is **false**. | | placementOnTop | boolean | No | false | Whether to display the popup above the component. The default value is **false**. |
| primaryButton | {<br/>value: string,<br/>action: () =&gt; void<br/>} | No | - | First button.<br/>**value**: text of the primary button in the popup.<br/>**action**: callback function for clicking the primary button. | | primaryButton | {<br/>value: string,<br/>action: () =&gt; void<br/>} | No | - | First button.<br/>**value**: text of the primary button in the popup.<br/>**action**: callback function for clicking the primary button. |
| secondaryButton | {<br/>value: string,<br/>action: () =&gt; void<br/>} | No | - | Second button.<br/>**value**: text of the secondary button in the popup.<br/>**action**: callback function for clicking the secondary button. | | secondaryButton | {<br/>value: string,<br/>action: () =&gt; void<br/>} | No | - | Second button.<br/>**value**: text of the secondary button in the popup.<br/>**action**: callback function for clicking the secondary button. |
| onStateChange | (isVisible: boolean) =&gt; void | No | - | Callback for the popup status change event. The parameter **isVisible** indicates the visibility of the popup. | | onStateChange | (isVisible: boolean) =&gt; void | No | - | Callback for the popup status change event. The parameter **isVisible** indicates the visibility of the popup. |
- CustomPopupOption<sup>8+</sup> - CustomPopupOptions<sup>8+</sup>
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| builder | () =&gt; any | Yes | - | Builder of the tooltip content. | | builder | () =&gt; any | Yes | - | Builder of the tooltip content. |
...@@ -39,16 +39,16 @@ None ...@@ -39,16 +39,16 @@ None
| onStateChange | (isVisible: boolean) =&gt; void | No | - | Callback for the popup status change event. The parameter **isVisible** indicates the visibility of the popup. | | onStateChange | (isVisible: boolean) =&gt; void | No | - | Callback for the popup status change event. The parameter **isVisible** indicates the visibility of the popup. |
- Placement<sup>8+</sup> enums - Placement<sup>8+</sup> enums
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| Left | The tooltip is on the left of the component. | | Left | The tooltip is on the left of the component. |
| Right | The tooltip is on the right of the component. | | Right | The tooltip is on the right of the component. |
| Top | The tooltip is on the top of the component. | | Top | The tooltip is on the top of the component. |
| Bottom | The tooltip is at the bottom of the component. | | Bottom | The tooltip is at the bottom of the component. |
| TopLeft | The tooltip is in the upper left corner of the component. | | TopLeft | The tooltip is in the upper left corner of the component. |
| TopRight | The tooltip is in the upper right corner of the component. | | TopRight | The tooltip is in the upper right corner of the component. |
| BottomLeft | The tooltip is in the lower left corner of the component. | | BottomLeft | The tooltip is in the lower left corner of the component. |
| BottomRight | The tooltip is in the lower right corner of the component. | | BottomRight | The tooltip is in the lower right corner of the component. |
## Example ## Example
......
...@@ -12,43 +12,43 @@ None ...@@ -12,43 +12,43 @@ None
## Events ## Events
| Name | Bubble Supported | Description | | Name | Bubble Supported | Description |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| onClick(callback: (event?: ClickEvent) =&gt; void) | No | Called when a click event occurs. For details about the event parameters, see [ClickEvent](#clickevent). | | onClick(callback: (event?: ClickEvent) =&gt; void) | No | Called when a click event occurs. For details about the event parameters, see [ClickEvent](#clickevent). |
### ClickEvent ### ClickEvent
| Name | Type | Description | | Name | Type | Description |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| screenX | number | X coordinate of the click relative to the left edge of the screen. | | screenX | number | X coordinate of the click relative to the left edge of the screen. |
| screenY | number | Y coordinate of the click relative to the upper edge of the screen. | | screenY | number | Y coordinate of the click relative to the upper edge of the screen. |
| x | number | X coordinate of the click relative to the left edge of the component being clicked. | | x | number | X coordinate of the click relative to the left edge of the component being clicked. |
| y | number | Y coordinate of the click relative to the upper edge of the component being clicked. | | y | number | Y coordinate of the click relative to the upper edge of the component being clicked. |
| target<sup>8+</sup> | EventTarget | Target element that is clicked. | | target<sup>8+</sup> | EventTarget | Target element that is clicked. |
| timestamp | number | Timestamp of the event. | | timestamp | number | Timestamp of the event. |
- EventTarget<sup>8+</sup> attributes - EventTarget<sup>8+</sup> attributes
| Name | Type | Description | | Name | Type | Description |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| area | Area | Area information of the target element.| | area | Area | Area information of the target element.|
- Area<sup>8+</sup> attributes - Area<sup>8+</sup> attributes
| Name | Type | Description | | Name | Type | Description |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| width | number | Width of the target element, in vp. | | width | number | Width of the target element, in vp. |
| height | number | Height of the target element, in vp. | | height | number | Height of the target element, in vp. |
| pos | Position | Position of the upper left corner of the target element relative to that of the parent element. | | position | Position | Position of the upper left corner of the target element relative to that of the parent element. |
| globalPos | Position | Position of the upper left corner of the target element relative to that of the page. | | globalPosition | Position | Position of the upper left corner of the target element relative to that of the page. |
- Position<sup>8+</sup> attributes - Position<sup>8+</sup> attributes
| Name | Type | Description | | Name | Type | Description |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| x | number | X-coordinate, in vp. | | x | number | X-coordinate, in vp. |
| y | number | Y-coordinate, in vp. | | y | number | Y-coordinate, in vp. |
## Example ## Example
......
# UI Development
- [ArkUI Overview](arkui-overview.md)
- JavaScript-based Web-like Development Paradigm
- [Overview](ui-js-overview.md)
- Framework
- [File Organization](js-framework-file.md)
- ["js" Tag](js-framework-js-tag.md)
- [app.js](js-framework-js-file.md)
- Syntax
- [HML](js-framework-syntax-hml.md)
- [CSS](js-framework-syntax-css.md)
- [JavaScript](js-framework-syntax-js.md)
- [Lifecycle](js-framework-lifecycle.md)
- [Resource Limitations and Access](js-framework-resource-restriction.md)
- [Multi-Language Capability](js-framework-multiple-languages.md)
- Building the UI
- [Component Overview](ui-js-building-ui-component.md)
- Building the Layout
- [Layout Description](ui-js-building-ui-layout-intro.md)
- [Adding Title and Paragraph Text](ui-js-building-ui-layout-text.md)
- [Adding an Image](ui-js-building-ui-layout-image.md)
- [Adding a Comment](ui-js-building-ui-layout-comment.md)
- [Adding a Container](ui-js-building-ui-layout-external-container.md)
- [Adding Interactions](ui-js-building-ui-interactions.md)
- [Developing Animations](ui-js-building-ui-animation.md)
- [Defining Gesture Events](ui-js-building-ui-event.md)
- [Defining Page Routes](ui-js-building-ui-routes.md)
- Common Component Development Guidelines
- Container Components
- [List Development](ui-js-components-list.md)
- [Dialog Development](ui-js-components-dialog.md)
- [Form Development](ui-js-components-form.md)
- [Stepper Development](ui-js-components-stepper.md)
- [Tabs Development](ui-js-component-tabs.md)
- [Swiper Development](ui-js-components-swiper.md)
- Basic Components
- [Text Development](ui-js-components-text.md)
- [Input Development](ui-js-components-input.md)
- [Button Development](ui-js-components-button.md)
- [Picker Development](ui-js-components-picker.md)
- [Image Development](ui-js-components-images.md)
- [Image-animator Development](ui-js-components-image-animator.md)
- [Rating Development](ui-js-components-rating.md)
- [Slider Development](ui-js-components-slider.md)
- [Chart Development](ui-js-components-chart.md)
- [Switch Development](ui-js-components-switch.md)
- [Toolbar Development](ui-js-components-toolbar.md)
- [Menu Development](ui-js-components-menu.md)
- [Marquee Development](ui-js-components-marquee.md)
- [Qrcode Development](ui-js-components-qrcode.md)
- [Search Development](ui-js-components-search.md)
- Canvas Development
- [CanvasRenderingContext2D](ui-js-components-canvasrenderingcontext2d.md)
- [Path2D](ui-js-components-path2d.md)
- [OffscreenCanvas](ui-js-components-offscreencanvas.md)
- [Grid-container Development](ui-js-components-calendar.md)
- Svg
- [Basics](ui-js-components-svg-overview.md)
- [Graph Drawing](ui-js-components-svg-graphics.md)
- [Path Drawing](ui-js-components-svg-path.md)
- [Text Drawing](ui-js-components-svg-text.md)
- Animation Development Guidelines
- CSS Animation
- [Defining Attribute Style Animations](ui-js-animate-attribute-style.md)
- [Defining Animations with the transform Attribute](ui-js-animate-transform.md)
- [Defining Animations with the background-position Attribute](ui-js-animate-background-position-style.md)
- [Defining Animations for SVG Components](ui-js-animate-svg.md)
- JS Animation
- [Component Animation](ui-js-animate-component.md)
- Interpolator Animation
- [Animation Effect](ui-js-animate-dynamic-effects.md)
- [Animation Frame](ui-js-animate-frame.md)
- [Custom Components](ui-js-custom-components.md)
- TypeScript-based Declarative Development Paradigm
- [Overview](ui-ts-overview.md)
- Framework Overview
- File Organization
- [Directory Structure](ts-framework-directory.md)
- [Rules for Accessing Application Code Files](ts-framework-file-access-rules.md)
- ["js" Tag](ts-framework-js-tag.md)
- Resource Access
- [Accessing Application Resources](ts-application-resource-access.md)
- [Accessing System Resources](ts-system-resource-access.md)
- [Media Resource Types](ts-media-resource-type.md)
- [Pixel Units](ts-pixel-units.md)
- [Types](ts-types.md)
- Declarative Syntax
- [Overview](ts-syntax-intro.md)
- General UI Description Specifications
- [Basic Concepts](ts-general-ui-concepts.md)
- Declarative UI Description Specifications
- [Configuration Without Parameters](ts-parameterless-configuration.md)
- [Configuration with Mandatory Parameters](ts-configuration-with-mandatory-parameters.md)
- [Attribute Configuration](ts-attribution-configuration.md)
- [Event Configuration](ts-event-configuration.md)
- [Child Component Configuration](ts-child-component-configuration.md)
- Componentization
- [@Component](ts-component-based-component.md)
- [@Entry](ts-component-based-entry.md)
- [@Preview](ts-component-based-preview.md)
- [@Builder](ts-component-based-builder.md)
- [@Extend](ts-component-based-extend.md)
- [@CustomDialog](ts-component-based-customdialog.md)
- [@Styles](ts-component-based-styles.md)
- About UI State Management
- [Basic Concepts](ts-ui-state-mgmt-concepts.md)
- Managing Component States
- [@State](ts-component-states-state.md)
- [@Prop](ts-component-states-prop.md)
- [@Link](ts-component-states-link.md)
- Managing Application States
- [AppStorage](ts-application-states-appstorage.md)
- [PersistentStorage](ts-application-states-apis-persistentstorage.md)
- [Environment](ts-application-states-apis-environment.md)
- Managing Other States
- [@Observed and @ObjectLink](ts-other-states-observed-objectlink.md)
- [@Consume and @Provide](ts-other-states-consume-provide.md)
- [@Watch](ts-other-states-watch.md)
- About Rendering Control Syntax
- [if/else](ts-rending-control-syntax-if-else.md)
- [ForEach](ts-rending-control-syntax-foreach.md)
- [LazyForEach](ts-rending-control-syntax-lazyforeach.md)
- About @Component
- [build Function](ts-function-build.md)
- [Initialization of Custom Components' Member Variables](ts-custom-component-initialization.md)
- [Custom Component Lifecycle Callbacks](ts-custom-component-lifecycle-callbacks.md)
- [Component Creation and Re-initialization](ts-component-creation-re-initialization.md)
- [About Syntactic Sugar](ts-syntactic-sugar.md)
- Common Component Development Guidelines
- [Button](ui-ts-basic-components-button.md)
- [Web](ui-ts-components-web.md)
- Common Layout Development Guidelines
- [Flex Layout](ui-ts-layout-flex.md)
- [Grid Layout](ui-ts-layout-grid-container.md)
- [Media Query](ui-ts-layout-mediaquery.md)
- Experiencing the Declarative UI
- [Creating a Declarative UI Project](ui-ts-creating-project.md)
- [Getting to Know Components](ui-ts-components.md)
- [Creating a Simple Page](ui-ts-creating-simple-page.md)
- Defining Page Layout and Connection
- [Building a Food Data Model](ui-ts-building-data-model.md)
- [Building a Food Category List Layout](ui-ts-building-category-list-layout.md)
- [Building a Food Category Grid Layout](ui-ts-building-category-grid-layout.md)
- [Implementing Page Redirection and Data Transmission](ui-ts-page-redirection-data-transmission.md)
...@@ -13,42 +13,20 @@ ArkUI is a UI development framework that provides what you'll need to develop ap ...@@ -13,42 +13,20 @@ ArkUI is a UI development framework that provides what you'll need to develop ap
- Page: the smallest unit for ArkUI application scheduling. You can design multiple pages for your application, manage their files on a per-page basis, and schedule page redirection through routing APIs, so as to implement decoupling of application functions. - Page: the smallest unit for ArkUI application scheduling. You can design multiple pages for your application, manage their files on a per-page basis, and schedule page redirection through routing APIs, so as to implement decoupling of application functions.
## Key Capabilities ## Key Features
- Diverse components: In addition to a wide range of basic components, such as components for text display, image display, and keypress interaction, ArkUI provides media components that support video playback. Better yet, it also provides polymorphic components, which can adapt to styles of different devices.
- Flexible layouts: Creating a responsive UI in ArkUI is easy, with our carefully-designed layout approaches: Besides the classic flexible layout capability, you also have access to the list, grid, and atomic layouts that auto-adapt to screen resolutions.
- UI components: In addition to a wide range of basic components, such as components for text display, image display, and keypress interaction, ArkUI provides media components that support video playback. Better yet, it also provides polymorphic components, which can adapt to styles of different devices.
- Layout: Creating a responsive UI in ArkUI is easy, with our carefully-designed layout approaches: Besides the classic flexible layout capability, you also have access to the list, grid, and atomic layouts that auto-adapt to screen resolutions.
- Animation: Apart from animations embedded in components, ArkUI offers additional animation features: attribute animation, transition animation, and custom animation. - Animation: Apart from animations embedded in components, ArkUI offers additional animation features: attribute animation, transition animation, and custom animation.
- UI interaction: ArkUI allows users to interact with your application UI properly, regardless of the system platform and input device. By default, the UI accepts input from touch gestures, remote controls, and mouse devices, with support for the event notification capability.
- Drawing: ArkUI offers advanced drawing capabilities that allow you to draw custom shapes with a range of editors, from images to fill colors and texts. - Drawing: ArkUI offers advanced drawing capabilities that allow you to draw custom shapes with a range of editors, from images to fill colors and texts.
- Interaction: ArkUI allows users to interact with your application UI properly, regardless of the system platform and input device. By default, the UI accepts input from touch gestures, remote controls, and mouse devices, with support for the event notification capability.
- Platform API channel: ArkUI provides an API extension mechanism through which platform capabilities are encapsulated to produce JavaScript APIs in a unified style. - Platform API channel: ArkUI provides an API extension mechanism through which platform capabilities are encapsulated to produce JavaScript APIs in a unified style.
- Two development paradigms: ArkUI comes with two development paradigms: JavaScript-based web-like development paradigm (web-like development paradigm for short) and TypeScript-based declarative development paradigm (declarative development paradigm for short). You can choose whichever development paradigm that aligns with your practice.
| Development Paradigm | Description | Applicable To | Intended Audience |
## Development Paradigms | -------- | -------- | -------- | -------- |
| Web-like development paradigm | Uses the classical three-stage programming model, in which OpenHarmony Markup Language (HML) is used for building layouts, CSS for defining styles, and JavaScript for adding processing logic. UI components are associated with data through one-way data-binding. This means that when data changes, the UI automatically updates with the new data. This development paradigm has a low learning curve for frontend web developers, allowing them to quickly transform existing web applications into ArkUI applications. | Small- and medium-sized applications and service widgets with simple UIs | Frontend web developers |
ArkUI comes with two development paradigms: JavaScript-based web-like development paradigm (web-like development paradigm for short) and TypeScript-based declarative development paradigm (declarative development paradigm for short). You can choose whichever development paradigm that aligns with your practice. | Declarative development paradigm | Uses the TypeScript programming language and extends the declarative UI syntax, providing UI drawing capabilities from three dimensions: component, animation, and state management. The programming mode used is closer to natural semantics. You can intuitively describe the UI without caring about how the framework implements UI drawing and rendering, leading to simplified and efficient development. With type annotations in TypeScript, you can enforce type checking at compile time. | Applications involving technological sophistication and teamwork | Mobile application and system application developers |
### Web-like Development Paradigm
The web-like development paradigm uses the classical three-stage programming model, in which OpenHarmony Markup Language (HML) is used for building layouts, CSS for defining styles, and JavaScript for adding processing logic. UI components are associated with data through one-way data-binding. This means that when data changes, the UI automatically updates with the new data. This development paradigm has a low learning curve for frontend web developers, allowing them to quickly transform existing web applications into ArkUI applications. It could be helpful if you are developing small- and medium-sized applications with simple UIs.
### Declarative Development Paradigm
The declarative development paradigm uses the TypeScript programming language and extends the declarative UI syntax, providing UI drawing capabilities from three dimensions: component, animation, and state management. The programming mode used is closer to natural semantics. You can intuitively describe the UI without caring about how the framework implements UI drawing and rendering, leading to simplified and efficient development. With type annotations in TypeScript, you can enforce type checking at compile time. If you are developing large applications, the declarative development paradigm is more applicable.
### Web-like Development Paradigm vs. Declarative Development Paradigm
| Development Paradigm | Language | UI Update Mode | Applicable To | Intended Audience |
| -------- | -------- | -------- | -------- | -------- |
| Web-like development paradigm | JavaScript | Data-driven | Applets and service widgets with simple UIs | Frontend web developers |
| Declarative development paradigm | Extended TypeScript (eTS) | Data-driven | Applications involving technological sophistication and teamwork | Mobile application and system application developers |
### Framework Structure ### Framework Structure
......
...@@ -20,19 +20,19 @@ language[-script-region].json ...@@ -20,19 +20,19 @@ language[-script-region].json
The following table describes the requirements for the qualifiers of resource file names. The following table describes the requirements for the qualifiers of resource file names.
Table1 Requirements for qualifier values Table 1 Requirements for qualifier values
| Qualifier Type | Description and Value Range | | Qualifier Type | Description and Value Range |
| -------- | -------- | | -------- | -------- |
| Language | Indicates the language used by the device. The value consists of two or three lowercase letters, for example, zh indicates Chinese, en indicates English, and mai indicates Maithili.<br/>For details about the value range, refer to ISO 639 (codes for the representation of names of languages). | | Language | Indicates the language used by the device. The value consists of two or three lowercase letters, for example, zh indicates Chinese, en indicates English, and mai indicates Maithili.<br/>For details about the value range, refer to ISO 639 (codes for the representation of names of languages). |
| Script | Indicates the script type used by the device. The value starts with one uppercase letter followed by three lowercase letters, for example, Hans indicates simplified Chinese and Hant indicates traditional Chinese.<br/>For details about the value range, refer to ISO 15924 (codes for the representation of names of scripts). | | Script | Indicates the script type used by the device. The value starts with one uppercase letter followed by three lowercase letters, for example, Hans indicates simplified Chinese and Hant indicates traditional Chinese.<br/>For details about the value range, refer to ISO 15924 (codes for the representation of names of scripts). |
| Country/Region | Indicates the country or region where a user is located. The value consists of two or three uppercase letters or three digits, for example, CN indicates China and GB indicates the United Kingdom.<br/>For details about the value range, refer to ISO 3166-1 (codes for the representation of names of countries and their subdivisions). | | Country/Region | Indicates the country or region where a user is located. The value consists of two or three uppercase letters or three digits, for example, CN indicates China and GB indicates the United Kingdom.<br/>For details about the value range, refer to ISO 3166-1 (codes for the representation of names of countries and their subdivisions). |
If there is no resource file of the locale that matches the system language, content in the en-US.json file will be used by default. If there is no resource file of the locale that matches the system language, content in the en-US.json file will be used by default.
The format of the resource file content is as follows: The format of the resource file content is as follows:
en-US.json **en-US.json**
``` ```
{ {
...@@ -55,8 +55,7 @@ Different languages have different matching rules for singular and plural forms. ...@@ -55,8 +55,7 @@ Different languages have different matching rules for singular and plural forms.
The following example takes en-US.json and ar-AE.json as examples: The following example takes en-US.json and ar-AE.json as examples:
**en-US.json**
en-US.json
``` ```
...@@ -97,18 +96,18 @@ Multi-language syntax used on application development pages (including simple fo ...@@ -97,18 +96,18 @@ Multi-language syntax used on application development pages (including simple fo
- Simple formatting - Simple formatting
Use the $t function to reference to resources of different locales. The $t function is available for both .hml and .js files. The system displays content based on a resource file path specified via $t and the specified resource file whose locale matches the current system language. Use the $t function to reference to resources of different locales. The $t function is available for both .hml and .js files. The system displays content based on a resource file path specified via $t and the specified resource file whose locale matches the current system language.
Table2 Simple formatting Table 2 Simple formatting
| Attribute | Type | Parameter | Mandatory | Description | | Attribute | Type | Parameter | Mandatory | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| $t | Function | See Table3 | Yes | Sets the parameters based on the system language, for example, this.$t('strings.hello'). | | $t | Function | See Table3 | Yes | Sets the parameters based on the system language, for example, this.$t('strings.hello'). |
Table3 $t function parameters Table 3 $t function parameters
| Parameter | Type | Mandatory | Description | | Parameter | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| path | string | Yes | Path of the language resource key | | path | string | Yes | Path of the language resource key |
| params | Array\|Object | No | Content used to replace placeholders during runtime. There are two types of placeholders available:<br/>- Named placeholder, for example, {name}. The actual content must be of the object type, for example, $t('strings.object', { name: 'Hello world' }).<br/>- Digit placeholder, for example, {0}. The actual content must be of the array type, for example, $t('strings.array', ['Hello world']. | | params | Array\|Object | No | Content used to replace placeholders during runtime. There are two types of placeholders available:<br/>- Named placeholder, for example, {name}. The actual content must be of the object type, for example, \```$t('strings.object', {name:'Hello world'})```.<br/>- Digit placeholder, for example, {0}. The actual content must be of the array type, for example, \```$t('strings.array', [Hello world']```. |
- Example code for simple formatting - Example code for simple formatting
...@@ -156,18 +155,18 @@ Multi-language syntax used on application development pages (including simple fo ...@@ -156,18 +155,18 @@ Multi-language syntax used on application development pages (including simple fo
``` ```
- Singular-plural formatting - Singular-plural formatting
Table4 Singular-plural formatting Table 4 Singular-plural formatting
| Attribute | Type | Parameter | Mandatory | Description | | Attribute | Type | Parameter | Mandatory | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| $tc | Function | See Table 5. | Yes | Converts between the singular and plural forms based on the system language, for example, this.$tc('strings.people').<br/>> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**:<br/>> The resource content is distinguished by the following JSON keys: zero, one, two, few, many, and other. | | $tc | Function | See Table 5. | Yes | Converts between the singular and plural forms based on the system language, for example, this.$tc('strings.people').<br/>> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>> The resource content is distinguished by the following JSON keys: zero, one, two, few, many, and other. |
Table5 $tc function parameters Table 5 $tc function parameters
| Parameter | Type | Mandatory | Description | | Parameter | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| path | string | Yes | Path of the language resource key | | path | string | Yes | Path of the language resource key |
| count | number | Yes | Number | | count | number | Yes | Number |
- Sample code for singular-plural formatting - Sample code for singular-plural formatting
......
# Defining Events # Defining Gesture Events
A gesture represents a semantic action (for example, tap, drag, or longpress) that can trigger one or more events. A gesture lifecycle may consist of multiple events from the start to the end of the gesture. Supported events are as follows:
Events mainly include gesture events for touchscreen devices. **Touch**
- **touchstart**: Triggered when the touch starts
## Gesture Events - **touchmove**: Triggered when the touch moves
A gesture represents a semantic action (for example, tap, drag, or longpress) that can trigger one or more events. A gesture lifecycle may consist of multiple events from the start to the end of the gesture. Supported events: - **touchcancel**: Triggered when the touch is interrupted, for example, by an incoming call notification or pop-up message
Touch - **touchend**: Triggered when the touch ends
- touchstart: Triggered when the touch starts
- touchmove: Triggered when the touch moves **Click**
- touchcancel: Triggered when the touch is interrupted, for example, by an incoming call notification or pop-up message **click**: Triggered when a user taps the screen quickly.
- touchend: Triggered when the touch ends **Longpress**
Click **longpress**: Triggered when a user keeps tapping the screen at the same position for a while.
click: Triggered when a user taps the screen quickly.
Longpress
longpress: Triggered when a user keeps tapping the screen at the same position for a while.
The following is an example: The following is an example:
......
# &lt;tabs&gt; Development # &lt;tabs&gt; Development
The &lt;tabs&gt; component is a common UI component for navigation. It allows quick access to different functions of an app. For details, see [tabs](../reference/arkui-js/js-components-container-tabs.md). The **&lt;tabs&gt;** component is a common UI component for navigation. It allows quick access to different functions of an app. For details, see [tabs](../reference/arkui-js/js-components-container-tabs.md).
## Creating Tabs ## Creating Tabs
Create a &lt;tabs&gt; component in the .hml file under pages/index. Create a **&lt;tabs&gt;** component in the .hml file under **pages/index**.
``` ```
<!-- index.hml --> <!-- index.hml -->
<div class="container" > <div class="container" >
<tabs> <tabs>
<tab-bar> <tab-bar>
<text>item1</text> <text>item1</text>
<text>item2</text> <text>item2</text>
</tab-bar> </tab-bar>
...@@ -25,7 +25,7 @@ Create a &lt;tabs&gt; component in the .hml file under pages/index. ...@@ -25,7 +25,7 @@ Create a &lt;tabs&gt; component in the .hml file under pages/index.
<text>content2</text> <text>content2</text>
</div> </div>
</tab-content> </tab-content>
</tabs> </tabs>
</div> </div>
``` ```
...@@ -51,13 +51,13 @@ Create a &lt;tabs&gt; component in the .hml file under pages/index. ...@@ -51,13 +51,13 @@ Create a &lt;tabs&gt; component in the .hml file under pages/index.
## Setting the Tabs Orientation ## Setting the Tabs Orientation
By default, the active tab of a &lt;tabs&gt; component is the one with the specified index. To show the &lt;tabs&gt; vertically, set the vertical attribute to true. By default, the active tab of a **&lt;tabs&gt;** component is the one with the specified **index**. To show the **&lt;tabs&gt;** vertically, set the **vertical** attribute to **true**.
``` ```
<!-- index.hml --> <!-- index.hml -->
<div class="container" style="background-color:#F1F3F5;"> <div class="container" style="background-color:#F1F3F5;">
<tabs index="1" vertical="true"> <tabs index="1" vertical="true">
<tab-bar > <tab-bar >
<text>item1</text> <text>item1</text>
<text style="margin-top: 50px;">item2</text> <text style="margin-top: 50px;">item2</text>
...@@ -76,7 +76,7 @@ By default, the active tab of a &lt;tabs&gt; component is the one with the speci ...@@ -76,7 +76,7 @@ By default, the active tab of a &lt;tabs&gt; component is the one with the speci
![en-us_image_0000001222967756](figures/en-us_image_0000001222967756.gif) ![en-us_image_0000001222967756](figures/en-us_image_0000001222967756.gif)
Set the mode attribute to enable the child components of the <tab-bar> to be evenly distributed. Set the scrollable attribute to disable scrolling of the <tab-content>. Set the **mode** attribute to enable the child components of the **&lt;tab-bar&gt;** to be evenly distributed. Set the **scrollable** attribute to disable scrolling of the **&lt;tab-content&gt;**.
``` ```
...@@ -102,9 +102,9 @@ Set the mode attribute to enable the child components of the <tab-bar> to be eve ...@@ -102,9 +102,9 @@ Set the mode attribute to enable the child components of the <tab-bar> to be eve
![en-us_image_0000001267647857](figures/en-us_image_0000001267647857.gif) ![en-us_image_0000001267647857](figures/en-us_image_0000001267647857.gif)
## Setting the Style ## Setting Styles
Set the background color, border, and tab-content layout of the &lt;tabs&gt; component. Set the background color, border, and tab-content layout of the **&lt;tabs&gt;** component.
``` ```
<!-- index.hml --> <!-- index.hml -->
...@@ -150,7 +150,8 @@ Set the mode attribute to enable the child components of the <tab-bar> to be eve ...@@ -150,7 +150,8 @@ Set the mode attribute to enable the child components of the <tab-bar> to be eve
margin-top: 10px; margin-top: 10px;
height: 300px; height: 300px;
color: blue; color: blue;
justify-content: center; align-items: center; justify-content: center;
align-items: center;
} }
``` ```
...@@ -159,13 +160,13 @@ Set the mode attribute to enable the child components of the <tab-bar> to be eve ...@@ -159,13 +160,13 @@ Set the mode attribute to enable the child components of the <tab-bar> to be eve
## Displaying the Tab Index ## Displaying the Tab Index
Add the change event for the &lt;tabs&gt; component to display the index of the current tab after tab switching. Add the **change** event for the **&lt;tabs&gt;** component to display the index of the current tab after tab switching.
``` ```
<!-- index.hml --> <!-- index.hml -->
<div class="container" style="background-color:#F1F3F5;"> <div class="container" style="background-color:#F1F3F5;">
<tabs class="tabs" onchange="tabChange"> <tabs class="tabs"onchange="tabChange">
<tab-bar class="tabBar"> <tab-bar class="tabBar">
<text class="tabBarItem">item1</text> <text class="tabBarItem">item1</text>
<text class="tabBarItem">item2</text> <text class="tabBarItem">item2</text>
...@@ -198,15 +199,15 @@ export default { ...@@ -198,15 +199,15 @@ export default {
![en-us_image_0000001222807772](figures/en-us_image_0000001222807772.gif) ![en-us_image_0000001222807772](figures/en-us_image_0000001222807772.gif)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> - A &lt;tabs&gt; can wrap at most one [<tab-bar>](../reference/arkui-js/js-components-container-tab-bar.md) and at most one [<tab-content>](../reference/arkui-js/js-components-container-tab-content.md). > - A **&lt;tabs&gt;** can wrap at most one [**&lt;tab-bar&gt;**](../reference/arkui-js/js-components-container-tab-bar.md) and at most one [**&lt;tab-content&gt;**](../reference/arkui-js/js-components-container-tab-content.md).
## Example Scenario ## Example Scenario
In this example, you can switch between tabs and the active tab has the title text in red with an underline below. In this example, you can switch between tabs and the active tab has the title text in red with an underline below.
Use the &lt;tabs&gt;, <tab-bar>, and <tab-content> components to implement tab switching. Then define the arrays and attributes. Add the change event to change the attribute values in the arrays so that the active tab has a different font color and an underline. Use the **&lt;tabs&gt;**, **&lt;tab-bar&gt;**, and **&lt;tab-content&gt;** components to implement tab switching. Then define the arrays and attributes. Add the **change** event to change the attribute values in the arrays so that the active tab has a different font color and an underline.
``` ```
......
# &lt;button&gt; Development # &lt;button&gt; Development
The&lt;button&gt;component can be used to set a capsule, circle, text, arc, or download button. For details, see [button](../reference/arkui-js/js-components-basic-button.md). The **&lt;button&gt;** component can be used to set a capsule, circle, text, arc, or download button. For details, see [button](../reference/arkui-js/js-components-basic-button.md).
## Creating a &lt;button&gt; Component ## Creating a &lt;button&gt; Component
Create a &lt;button&gt; component in the .hml file under pages/index. Create a **&lt;button&gt;** component in the .hml file under **pages/index**.
``` ```
...@@ -20,6 +20,8 @@ Create a &lt;button&gt; component in the .hml file under pages/index. ...@@ -20,6 +20,8 @@ Create a &lt;button&gt; component in the .hml file under pages/index.
``` ```
/* xxx.css */ /* xxx.css */
.container { .container {
width: 100%;
height: 100%;
flex-direction: column; flex-direction: column;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
...@@ -32,7 +34,9 @@ Create a &lt;button&gt; component in the .hml file under pages/index. ...@@ -32,7 +34,9 @@ Create a &lt;button&gt; component in the .hml file under pages/index.
## Setting the Button Type ## Setting the Button Type
Set the type attribute of the &lt;input&gt; component to button, date, or any of the supported values. Set the **type** attribute of the **&lt;input&gt;** component to **button**, **date**, or any of the supported values.
``` ```
<!-- xxx.hml --> <!-- xxx.hml -->
...@@ -42,9 +46,13 @@ Set the type attribute of the &lt;input&gt; component to button, date, or any of ...@@ -42,9 +46,13 @@ Set the type attribute of the &lt;input&gt; component to button, date, or any of
</div> </div>
``` ```
``` ```
/* xxx.css */ /* xxx.css */
.container { .container {
width: 100%;
height: 100%;
background-color: #F1F3F5; background-color: #F1F3F5;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
...@@ -70,17 +78,19 @@ Set the type attribute of the &lt;input&gt; component to button, date, or any of ...@@ -70,17 +78,19 @@ Set the type attribute of the &lt;input&gt; component to button, date, or any of
![en-us_image_0000001222967744](figures/en-us_image_0000001222967744.png) ![en-us_image_0000001222967744](figures/en-us_image_0000001222967744.png)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> - For capsule buttons, border-related styles are not supported. > - For capsule buttons, border-related styles are not supported.
> >
> - For circle buttons, text-related styles are not supported. > - For circle buttons, text-related styles are not supported.
> >
> - For text buttons, the text size is adaptive, and radius, width, and height cannot be set. The background-color style is not supported when the background is completely transparent. > - For text buttons, the text size is adaptive, and **radius**, **width**, and **height** cannot be set. The **background-color** style is not supported when the background is completely transparent.
> >
> - If the icon used by the&lt;button&gt;component is from the cloud, you must declare the ohos.permission.INTERNET permission in the config.json file under the resources folder. > - If the icon used by the **&lt;button&gt;** component is from the cloud, you must declare the **ohos.permission.INTERNET** permission in the **config.json** file under the **resources** folder.
Sample code for declaring the **ohos.permission.INTERNET** permission in the **config.json** file under the **resources** folder:
Sample code for declaring the ohos.permission.INTERNET permission in the config.json file under the resources folder:
``` ```
<!-- config.json --> <!-- config.json -->
...@@ -94,7 +104,7 @@ Sample code for declaring the ohos.permission.INTERNET permission in the config. ...@@ -94,7 +104,7 @@ Sample code for declaring the ohos.permission.INTERNET permission in the config.
## Showing the Download Progress ## Showing the Download Progress
Add the progress method to the&lt;button&gt;component to display the download progress in real time. Add the **progress** method to the **&lt;button&gt;** component to display the download progress in real time.
``` ```
...@@ -171,15 +181,16 @@ export default { ...@@ -171,15 +181,16 @@ export default {
![en-us_image_0000001223287652](figures/en-us_image_0000001223287652.gif) ![en-us_image_0000001223287652](figures/en-us_image_0000001223287652.gif)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> > - The **setProgress** method supports only buttons of the download type.
> The setProgress method supports only buttons of the download type.
## Example Scenario ## Example Scenario
Switch between the button types for different types of text. Switch between the button types for different types of text.
``` ```
<!-- xxx.hml --> <!-- xxx.hml -->
<div class="container"> <div class="container">
...@@ -197,6 +208,8 @@ Switch between the button types for different types of text. ...@@ -197,6 +208,8 @@ Switch between the button types for different types of text.
</div> </div>
``` ```
``` ```
/* xxx.css */ /* xxx.css */
.container { .container {
...@@ -243,6 +256,8 @@ Switch between the button types for different types of text. ...@@ -243,6 +256,8 @@ Switch between the button types for different types of text.
} }
``` ```
``` ```
// xxx.js // xxx.js
export default { export default {
......
# &lt;grid-container&gt; Development
The **&lt;grid-container&gt;** component is the root container of the grid layout. Within the root container, you can use **&lt;grid-row&gt;** and **&lt;grid-col&gt;** for the grid layout. For details, see [grid-container](../reference/arkui-js/js-components-grid-container.md).
## Creating a &lt;grid-container&gt; Component
Create a **&lt;grid-container&gt;** component in the .hml file under **pages/index** and add a [**&lt;grid-row&gt;**](../reference/arkui-js/js-components-grid-row.md) child component.
```
<!-- index.hml -->
<div class="container">
<grid-container id="mygrid" columns="5" gutter="20px" style="background-color: pink;">
<grid-row style="height:100px;justify-content:space-around;width: 80%;background-color: #f67002;margin-left:
10%;"></grid-row>
<grid-row style="height:300px;justify-content:space-around;background-color: #ffcf00;width: 100%;"></grid-row>
<grid-row style="height:150px;justify-content:space-around;background-color: #032cf8;width: 100%;"></grid-row>
</grid-container>
</div>
```
```
/* xxx.css */
.container{
flex-direction: column;
background-color: #F1F3F5;
width: 100%;
justify-content: center;
align-items: center;
}
```
![en-us_image_0000001276162725](figures/en-us_image_0000001276162725.png)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> **&lt;grid-container&gt;** supports only **&lt;grid-row&gt;** as a child component.
## Methods
Click the **&lt;grid-container&gt;** component to call the **getColumns**, **getColumnWidth**, and **getGutterWidth** methods to return the number of columns in the grid container, and column width and gutter width of the grid container. Press and hold the component to call the **getSizeType** method to return the size-responsive type of the grid container (**xs**|**sm**|**md**|**lg**).
```
<!-- index.hml -->
<div class="container">
<grid-container id="mygrid" columns="6" gutter="20px" style="background-color: pink;padding-top: 100px;"
onclick="getColumns" onlongpress="getSizeType">
<grid-row style="height:100px;justify-content:space-around;background-color: #4cedf3;width: 20%;margin-left:
40%;"></grid-row>
<grid-row style="height:150px;justify-content:space-around;background-color: #4cbff3;width: 50%;margin-left:
25%;"></grid-row>
<grid-row style="height:200px;justify-content:space-around;background-color: #465ff6;width: 80%;margin-left:
10%;"></grid-row>
<grid-row style="height:200px;justify-content:space-around;background-color: #5011ec;width: 100%;"></grid-row>
</grid-container>
</div>
```
```
/* xxx.css */
.container{
flex-direction: column;
background-color: #F1F3F5;
width: 100%;
justify-content: center;
align-items: center;
}
```
```
// index.js
import prompt from '@system.prompt';
export default {
data:{
gutterWidth:'',
columnWidth:'',
columns:'',
},
getColumns(){
this.$element('mygrid').getColumnWidth((result)=>{
this.columnWidth = result;
})
this.$element('mygrid').getGutterWidth((result)=>{
this.gutterWidth = result;
})
this.$element('mygrid').getColumns((result)=>{
this.columns= result;
})
setTimeout(()=>{
prompt.showToast({duration:5000,message:'columnWidth:'+this.columnWidth+',gutterWidth:'+
this.gutterWidth+',getColumns:'+this.columns})
})
},
getSizeType(){
this.$element('mygrid').getSizeType((result)=>{
prompt.showToast({duration:2000,message:'get size type:'+result})
})
},
}
```
![en-us_image_0000001231843088](figures/en-us_image_0000001231843088.gif)
## Adding &lt;grid-col&gt;
After adding a **&lt;grid-row&gt;** child component to **&lt;grid-container&gt;**, add a **&lt;grid-col&gt;** child component to **&lt;grid-row&gt;** to form a layout.
```
<!-- index.hml -->
<div class="container">
<grid-container id="mygrid" columns="4" gutter="0" style="background-color: pink;" onclick="getColumns" onlongpress="getSizeType">
<grid-row style="height: 100px;justify-content: space-around;background-color: #4cbff3;width: 100%;">
<grid-col span="0">
<div style="align-items: center;justify-content: center;height: 100%;width: 100%;">
<text style="color: dodgerblue;" onclick="getCol">top</text>
</div>
</grid-col>
</grid-row>
<grid-row style="height:500px;justify-content:space-around;background-color: #3b55ef;width: 100%;">
<grid-col span="0" style="width: 20%;">
<div style="align-items: center;justify-content: center;height: 100%;width: 100%;">
<text style="color: dodgerblue;">left</text>
</div>
</grid-col>
<grid-col span="0" style="background-color:orange;width: 80%;">
<div style="width: 100%;height: 100%;align-items: center;justify-content: center;">
<text>right</text>
</div>
</grid-col>
</grid-row>
<grid-row style="height: 100px;justify-content: space-around;background-color: #4cbff3;width: 100%;">
<grid-col style="background-color:#c075ef;" span="0">
<div style="width: 100%;height: 100%;padding: 20px;align-items: center;justify-content: center;">
<text>bottom</text>
</div>
</grid-col>
</grid-row>
</grid-container>
</div>
```
```
/* xxx.css */
.container{
flex-direction: column;
background-color: #F1F3F5;
width: 100%;
justify-content: center;
align-items: center;
}
text{
color: white;
font-size: 40px;
```
![en-us_image_0000001231683124](figures/en-us_image_0000001231683124.png)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> **&lt;grid-row&gt;** supports only **&lt;grid-col&gt;** as a child component. You can add content only to **&lt;grid-col&gt;**.
## Example Scenario
In this example, the content in the list is output cyclically to create a grid layout. When the user pulls down the screen, the **refresh** method is triggered. In this case, a piece of data is added to the list and **setTimeout** is set to refresh the request data.
```
<!-- index.hml -->
<div class="container">
<refresh refreshing="{{fresh}}" onrefresh="refresh">
<grid-container id="mygrid" gutter="20" style="margin: 10px;">
<grid-row style="height:200px;width: 100%;background-color: #e7e7e2;margin-top: 50px; padding: 0px 20px;border-radius: 15px;" for="item in list">
<grid-col span="0" style="width: 40%;">
<div style="align-items: center;justify-content: center">
<image src="{{item.src}}" style="object-fit: contain;border-radius: 30px;"></image>
</div>
</grid-col>
<grid-col span="0" style="width: 60%;">
<div style="align-items: center;justify-content: center;width: 100%;height: 100%;text-align: center;">
<text>image{{item.id}}</text>
</div>
</grid-col>
</grid-row>
</grid-container>
</refresh>
</div>
```
```
/* xxx.css */
.container{
flex-direction: column;
background-color: #F1F3F5;
width: 100%;
}
text{
color: #0a0aef;
font-size: 60px;
}
```
```
// index.js
import prompt from '@system.prompt';
export default {
data:{
list:[
{src:'common/images/1.png',id:'1'},
{src:'common/images/2.png',id:'2'},
{src:'common/images/3.png',id:'3'}
],
fresh:false
},
refresh(e) {
prompt.showToast({
message: 'refreshing'
})
var that = this;
that.fresh = e.refreshing;
setTimeout(function () {
that.fresh = false;
that.list.unshift({src: 'common/images/4.png',id:'4'});
prompt.showToast({
message: 'succeed'
})
}, 2000)
}
}
```
![en-us_image_0000001276003501](figures/en-us_image_0000001276003501.gif)
# &lt;canvas&gt; Development
The **&lt;canvas&gt;** component provides a canvas for drawing customized graphics. For details, see [canvas](../reference/arkui-js/js-components-canvas-canvas.md).
## Creating a &lt;canvas&gt; Component
Create a **&lt;canvas&gt;** component in the .hml file under **pages/index**.
```
<!-- xxx.hml -->
<div class="container">
<canvas></canvas>
</div>
```
```
/* xxx.css */
.container{
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
canvas{
background-color: #00ff73;
}
```
![en-us_image_0000001232162316](figures/en-us_image_0000001232162316.png)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> - The default background color of the **&lt;canvas&gt;** component is the same as that of the parent component.
>
> - The default width and height of **&lt;canvas&gt;** are 300 px and 150 px, respectively.
## Adding Styles
Set **width**, **height**, **background-color**, and **border** of the **&lt;canvas&gt;** component.
```
<!-- xxx.hml -->
<div class="container">
<canvas></canvas>
</div>
```
```
/* xxx.css */
.container{
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
canvas{
width: 500px;
height: 500px;
background-color: #fdfdfd;
border: 5px solid red;
}
```
![en-us_image_0000001231843104](figures/en-us_image_0000001231843104.png)
## Adding Events
Add the long press event to the **&lt;canvas&gt;** component. When the event is triggered, the value of **dataUrl** (image information returned by the **toDataURL** method) of the **&lt;canvas&gt;** component can be obtained and printed in the text area below.
```
<!-- xxx.hml -->
<div class="container">
<canvas ref="canvas1" onlongpress="getUrl"></canvas>
<text>dataURL</text>
<text class="content">{{dataURL}}</text>
</div>
```
```
/* xxx.css */.container{ flex-direction: column; justify-content: center; align-items: center; background-color: #F1F3F5;}canvas{ width: 500px; height: 500px; background-color: #fdfdfd; border: 5px solid red;
margin-bottom: 50px;
}.content{ border: 5px solid blue; padding: 10px; width: 90%; height: 400px; overflow: scroll;}
```
```
// xxx.js
import prompt from '@system.prompt';
export default {
data:{
dataURL:null,
antialia: false,
porc:'open',
},
onShow(){
let el = this.$refs.canvas1;
let ctx = el.getContext("2d");
ctx.strokeRect(100,100,300,300);
},
getUrl(){
let el = this.$refs.canvas1;
let dataUrl = el.toDataURL();
this.dataURL = dataUrl;
prompt.showToast({duration:2000,message:"long press,get dataURL"});
}
}
```
![en-us_image_0000001276003513](figures/en-us_image_0000001276003513.gif)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> The **&lt;canvas&gt;** component cannot be created in **onInit** or **onReady**.
# CanvasRenderingContext2D
Use **CanvasRenderingContext2D** to draw objects such as graphics, texts, line segments, and images on the **&lt;canvas&gt;** component. For details, see [CanvasRenderingContext2D](../reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md).
## Drawing Line Segments
Use **moveTo** and **lineTo** to draw a line segment. Use the **closePath** method to end current path, obtaining a closed path. Set **quadraticCurveTo** (quadratic bezier curve) or **bezierCurveTo** (cubic bezier curve) to draw a graphic.
```
<!-- xxx.hml -->
<div class="container">
<canvas ref="canvas1"></canvas>
<select @change="change">
<option value="value1"> line </option>
<option value="value2"> quadratic </option>
<option value="value3"> bezier </option>
<option value="value4"> arc/ellipse </option>
<option value="value5"> lineJoin/miterLimit </option>
</select>
</div>
```
```
/* xxx.css */
.container{
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
canvas{
width: 600px;
height: 500px;
background-color: #fdfdfd;
border: 5px solid red;
}
select{
margin-top: 50px;
width: 250px;
height: 100px;
background-color: white;
}
```
```
// xxx.js
import prompt from '@system.prompt';
export default {
data:{
el: null,
ctx: null,
},
onShow(){
this.el = this.$refs.canvas1;
this.ctx = this.el.getContext("2d",{antialias: true});
// Clear the contents on the canvas.
this.ctx.clearRect(0, 0, 600, 500);
// Create a drawing path.
this.ctx.beginPath();
// Square off the endpoints of the line.
this.ctx.lineCap = 'butt';
// Border width
this.ctx.lineWidth = 15;
// Create a drawing path.
this.ctx.beginPath();
// Move a drawing path from the current point to a target position.
this.ctx.moveTo(200, 100);
// Connect the current point to a target position.
this.ctx.lineTo(400, 100);
// Stroke a path.
this.ctx.stroke();
this.ctx.beginPath();
// Round the endpoints of the line.
this.ctx.lineCap = 'round';
this.ctx.moveTo(200, 200);
this.ctx.lineTo(400, 200);
this.ctx.stroke();
// Square off the endpoints of the line.
this.ctx.beginPath();
this.ctx.lineCap = 'square';
this.ctx.moveTo(200, 300);
this.ctx.lineTo(400, 300);
this.ctx.stroke();
},
change(e){
if(e.newValue == 'value1'){
this.el = this.$refs.canvas1;
this.ctx = this.el.getContext("2d",{antialias: true});
this.ctx.clearRect(0, 0, 600, 500);
// Top
this.ctx.beginPath();
this.ctx.lineCap = 'butt';
this.ctx.moveTo(200, 100);
this.ctx.lineTo(400, 100);
this.ctx.stroke();
// Center
this.ctx.beginPath();
this.ctx.lineCap = 'round';
this.ctx.moveTo(200, 200);
this.ctx.lineTo(400, 200);
this.ctx.stroke();
// Bottom
this.ctx.beginPath();
this.ctx.lineCap = 'square';
this.ctx.moveTo(200, 300);
this.ctx.lineTo(400, 300);
this.ctx.stroke();
}else if(e.newValue == 'value2'){
this.ctx.clearRect(0, 0, 600, 500);
// Top
this.ctx.beginPath();
this.ctx.moveTo(100, 150);
// Path of the quadratic bezier curve
this.ctx.quadraticCurveTo(300, 50, 500, 150);
this.ctx.stroke();
// Left
this.ctx.beginPath();
this.ctx.moveTo(200, 150);
this.ctx.quadraticCurveTo(250, 250, 250, 400);
this.ctx.stroke();
// Right
this.ctx.beginPath();
this.ctx.moveTo(400, 150);
this.ctx.quadraticCurveTo(350, 250, 350, 400);
this.ctx.stroke();
}else if(e.newValue == 'value3'){
this.ctx.clearRect(0, 0, 600, 500);
// Bottom
this.ctx.beginPath();
this.ctx.moveTo(100, 200);
// Path of the cubic bezier curve
this.ctx.bezierCurveTo(150, 100, 200, 100,250, 200);
this.ctx.stroke();
// Left
this.ctx.beginPath();
this.ctx.moveTo(350, 200);
this.ctx.bezierCurveTo(400, 100, 450, 100,500, 200);
this.ctx.stroke();
// Right
this.ctx.beginPath();
this.ctx.moveTo(200, 350);
this.ctx.bezierCurveTo(250, 500, 350, 500, 400, 350);
this.ctx.stroke();
}else if(e.newValue == 'value4'){
this.ctx.clearRect(0, 0, 600, 500);
this.ctx.beginPath();
this.ctx.moveTo(100, 200);
// Arc
this.ctx.arcTo(150, 300, 350, 300, 150);
this.ctx.stroke();
this.ctx.beginPath();
// Ellipse
this.ctx.ellipse(400, 250, 50, 100, Math.PI * 0.25, Math.PI * 0.5 , Math.PI , 1);
this.ctx.stroke();
}else if(e.newValue == 'value5'){
this.ctx.clearRect(0, 0, 600, 500);
// Upper left
this.ctx.beginPath();
// Draw a sector centered at the common endpoint of connected line segments.
this.ctx.lineJoin = 'round';
this.ctx.moveTo(100, 100);
this.ctx.lineTo(200, 200);
this.ctx.lineTo(100, 250);
this.ctx.stroke();
// lower left
this.ctx.beginPath();
// Fill a triangular between the common endpoint of connected segments.
this.ctx.lineJoin = 'bevel';
this.ctx.moveTo(100, 300);
this.ctx.lineTo(200, 400);
this.ctx.lineTo(100, 450);
this.ctx.stroke();
// Top right
this.ctx.beginPath();
// Distance between the internal angle and exterior angle at the intersection of lines
this.ctx.lineJoin = 'miter';
this.ctx.miterLimit = 3;
this.ctx.moveTo(400, 100);
this.ctx.lineTo(450, 200);
this.ctx.lineTo(400, 250);
// Draw a closed path.
this.ctx.closePath();
this.ctx.stroke();
// Lower right
this.ctx.beginPath();
this.ctx.lineJoin = 'miter';
this.ctx.miterLimit = 10;
this.ctx.moveTo(400, 300);
this.ctx.lineTo(450, 400);
this.ctx.lineTo(400, 450);
this.ctx.closePath();
this.ctx.stroke();
}
},
}
```
![en-us_image_0000001232162320](figures/en-us_image_0000001232162320.gif)
## Drawing Border
Globally define the canvas (**el**) and brush (**ctx**), and create a rectangle with the border width of 5 upon initialization. Change the border width (**lineWidth**), color (**strokeStyle**), and line dash level (**setLineDash**). Add the **change** event to the **&lt;select&gt;** component. The **change** event will be triggered upon selection and the changed image will be displayed.
```
<!-- xxx.hml -->
<div class="container">
<canvas ref="canvas1"></canvas>
<select @change="change">
<option value="value1">strokeRect</option>
<option value="value2">arc</option>
<option value="value3">lineDashRect</option>
<option value="value4">fillRect</option>
</select>
</div>
```
```
/* xxx.css */
.container{
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
canvas{
width: 600px;
height: 500px;
background-color: #fdfdfd;
border: 5px solid red;
}
select{
margin-top: 50px;
width: 250px;
height: 100px;
background-color: white;
}
```
```
// xxx.js
import prompt from '@system.prompt';
export default {
data:{
el: null,
ctx: null,
},
onShow(){
this.el = this.$refs.canvas1;
this.ctx = this.el.getContext("2d",{antialias: true});
this.ctx.lineWidth = 5;
this.ctx.strokeRect(200, 150, 200, 200);
},
change(e){
if(e.newValue == 'value1'){
// Clear the contents on the canvas.
this.ctx.clearRect(0,0,600,500);
// Border width
this.ctx.lineWidth = 5;
// Border color
this.ctx.strokeStyle = '#110000';
// Line dash level of the border
this.ctx.setLineDash([0,0]);
// Draw a stroked rectangle.
this.ctx.strokeRect(200, 150, 200, 200);
}else if(e.newValue == 'value2'){
this.ctx.clearRect(0,0,600,500);
this.ctx.lineWidth = 30;
this.ctx.strokeStyle = '#0000ff';
this.ctx.setLineDash([0,0]);
// Draw a circle.
this.ctx.arc(300, 250, 150,0,6.28);
// Draw borders.
this.ctx.stroke();
}else if(e.newValue == 'value3'){
this.ctx.clearRect(0,0,600,500);
this.ctx.lineWidth = 5;
this.ctx.setLineDash([5,5]);
this.ctx.strokeRect(200, 150, 200, 200);
}else if(e.newValue == 'value4'){
this.ctx.clearRect(0,0,600,500);
// Draw and fill a rectangle.
this.ctx.fillStyle = '#0000ff';
this.ctx.fillRect(200, 150, 200, 200);
}
},
}
```
![en-us_image_0000001232003004](figures/en-us_image_0000001232003004.gif)
## Setting Gradient Fill Colors
Add the **createLinearGradient** and **createRadialGradient** attributes to create a gradient container, use the **addColorStop** method to add multiple color blocks to form a gradient color, and set **fillStyle** as **gradient** to apply the gradient color to a rectangle. Then set the shadow blur level by using **shadowBlur**, the shadow color by using **shadowColor**, and the shadow offset by using **shadowOffset**.
```
<!-- xxx.hml -->
<div class="container">
<canvas ref="canvas1"></canvas>
<select @change="change">
<option value="value1">LinearGradient</option>
<option value="value2">RadialGradient</option>
<option value="value3">shadowBlur</option>
<option value="value4">shadowOffset</option>
</select>
</div>
```
```
/* xxx.css */
.container{
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
canvas{
width: 600px;
height: 500px;
background-color: #fdfdfd;
border: 5px solid red;
}
select{
margin-top: 50px;
width: 250px;
height: 100px;
background-color: white;
}
```
```
// xxx.js
import prompt from '@system.prompt';
export default {
data:{
el: null,
ctx: null,
},
onShow(){
this.el = this.$refs.canvas1;
this.ctx = this.el.getContext("2d",{antialias: true});
// Create a linear gradient.
let gradient = this.ctx.createLinearGradient(100,100, 400,300);
// Add gradient colors.
gradient.addColorStop(0.0, 'red');
gradient.addColorStop(0.7, 'white');
gradient.addColorStop(1.0, 'green');
// Apply the gradient.
this.ctx.fillStyle = gradient;
this.ctx.fillRect(100, 100, 400, 300);
},
change(e){
if(e.newValue == 'value1'){
// Clear the contents on the canvas.
this.ctx.clearRect(0,0,600,500);
let gradient = this.ctx.createLinearGradient(100,100, 400,300);
gradient.addColorStop(0.0, 'red');
gradient.addColorStop(0.7, 'white');
gradient.addColorStop(1.0, 'green');
this.ctx.fillStyle = gradient;
// Set the level of shadow blur.
this.ctx.shadowBlur = 0;
// Set the distance that shadows will be offset vertically.
this.ctx.shadowOffsetY = 0;
// Set the distance that shadows will be offset horizontally.
this.ctx.shadowOffsetX = 0;
this.ctx.fillRect(100, 100, 400, 300);
}else if(e.newValue == 'value2'){
this.ctx.clearRect(0,0,600,500);
// Create a radial gradient.
let gradient = this.ctx.createRadialGradient(300,250,20,300,250,100);
gradient.addColorStop(0.0, 'red');
gradient.addColorStop(0.7, 'white');
gradient.addColorStop(1.0, 'green');
this.ctx.shadowBlur = 0;
this.ctx.shadowOffsetY = 0;
this.ctx.shadowOffsetX = 0;
this.ctx.fillStyle = gradient;
this.ctx.fillRect(100, 100, 400, 300);
}else if(e.newValue == 'value3'){
this.ctx.clearRect(0,0,600,500);
let gradient = this.ctx.createLinearGradient(100,100, 400,400);
gradient.addColorStop(0.0, 'red');
gradient.addColorStop(0.5, 'white');
gradient.addColorStop(1, '#17ea35');
// Set the level of shadow blur.
this.ctx.shadowBlur = 30;
// Set the shadow color.
this.ctx.shadowColor = 'rgb(229, 16, 16)';
this.ctx.fillStyle = gradient;
this.ctx.fillRect(100, 100, 400, 300);
}else if(e.newValue == 'value4'){
this.ctx.clearRect(0,0,600,500);
this.ctx.clearRect(0,0,600,500);
let gradient = this.ctx.createRadialGradient(300,250,20,300,250,200);
gradient.addColorStop(0.0, 'red');
gradient.addColorStop(0.5, 'white');
gradient.addColorStop(1, '#17ea35');
// Set the level of shadow blur.
this.ctx.shadowBlur = 30;
this.ctx.shadowOffsetY = 30;
// Set the shadow color.
this.ctx.shadowColor = 'rgb(23, 1, 1)';
this.ctx.fillStyle = gradient;
this.ctx.fillRect(100, 100, 400, 300);
}
},
}
```
![en-us_image_0000001231683148](figures/en-us_image_0000001231683148.gif)
## Filling Texts
Create a text and use the **fillText** method to write the text on the canvas. Use the **globalAlpha** attribute to change the baseline transparency to avoid the text being hidden by the baseline. Then set the **textAlign** and **textBaseline** attributes to determine the text position based on the baseline.
```
<!-- xxx.hml -->
<div class="container">
<canvas ref="canvas1"></canvas>
<select @change="change">
<option value="value1">text</option>
<option value="value2">textBaseline</option>
<option value="value3">textAlign</option>
</select>
</div>
```
```
/* xxx.css */
.container{
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
canvas{
width: 600px;
height: 500px;
background-color: #fdfdfd;
border: 5px solid red;
}
select{
margin-top: 50px;
width: 250px;
height: 100px;
background-color: white;
}
```
```
// xxx.js
import prompt from '@system.prompt';
export default {
data:{
el: null,
ctx: null,
},
onShow(){
this.el = this.$refs.canvas1;
this.ctx = this.el.getContext("2d",{antialias: true});
// Create a text.
let text = "Hello World";
// Set the font.
this.ctx.font = '30px';
this.ctx.fillText("with:"+this.ctx.measureText(text).width, 200, 300);
// Set the fill text.
this.ctx.fillText(text, 200, 250);
},
change(e){
if(e.newValue == 'value1'){
// Clear the contents on the canvas.
this.ctx.clearRect(0,0,600,500);
// Start a new path.
this.ctx.beginPath();
// Initialize the textAlign value.
this.ctx.textAlign = 'left';
// Initialize textBaseline.
this.ctx.textBaseline = 'alphabetic';
// Set the font.
this.ctx.font = '30px';
let text = "Hello World";
// Obtain the font width.
this.ctx.fillText("with:"+this.ctx.measureText(text).width, 200, 300);
// Set the fill text.
this.ctx.fillText(text, 200, 250);
}else if(e.newValue == 'value2'){
this.ctx.clearRect(0,0,600,500);
this.ctx.beginPath();
// Set the Alpha value.
this.ctx.globalAlpha = 0.1;
// Set the line width.
this.ctx.lineWidth = 10;
// Set the line segment color.
this.ctx.strokeStyle = '#0000ff';
// Move from the current point to a target position.
this.ctx.moveTo(0, 240);
// Connect the current point to a target position.
this.ctx.lineTo(600, 240);
this.ctx.stroke();
this.ctx.font = '35px';
this.ctx.globalAlpha = 1;
// Initialize the textAlign value.
this.ctx.textAlign = 'left';
// Set textBaseline.
this.ctx.textBaseline = 'top';
this.ctx.fillText('Top', 50, 240);
this.ctx.textBaseline = 'bottom';
this.ctx.fillText('Bottom', 200, 240);
this.ctx.textBaseline = 'middle';
this.ctx.fillText('Middle', 400, 240);
}else if(e.newValue == 'value3'){
// Clear the contents on the canvas.
this.ctx.clearRect(0,0,600,500);
this.ctx.beginPath();
this.ctx.globalAlpha = 0.1;
this.ctx.lineWidth = 10;
this.ctx.strokeStyle = '#0000ff';
this.ctx.moveTo(300, 0);
this.ctx.lineTo(300, 500);
this.ctx.stroke();
this.ctx.font = '35px';
this.ctx.globalAlpha = 1;
// Initialize textBaseline.
this.ctx.textBaseline = 'alphabetic';
// Set textAlign.
this.ctx.textAlign = 'left';
this.ctx.fillText('textAlign=left',300, 100);
this.ctx.textAlign = 'center';
this.ctx.fillText('textAlign=center',300, 250);
this.ctx.textAlign = 'right';
this.ctx.fillText('textAlign=right',300, 400);
}
}
}
```
![en-us_image_0000001276162745](figures/en-us_image_0000001276162745.gif)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> In the **ltr** layout mode, the value **start** equals **left**. In the **rtl** layout mode, the value **start** equals **right**.
## Adding Images
After creating an image object, use the **drawImage** attribute to draw the image and set animation styles such as scaling, translating, and rotating.
```
<!-- xxx.hml -->
<div class="container">
<div class="content">
<canvas ref="canvas0"></canvas>
<text onclick="change">change</text>
<canvas ref="canvas1"></canvas>
<text onclick="rotate">rotate</text>
<canvas ref="canvas2"></canvas>
<text onclick="scale">scale</text>
<canvas ref="canvas3"></canvas>
<text onclick="translate" style="width: 300px;">translate</text>
<canvas ref="canvas4"></canvas>
<text onclick="transform" style="width: 300px;">transform</text>
<canvas ref="canvas5"></canvas>
<text onclick="setTransform" style="width: 300px;">setTransform</text>
<canvas ref="canvas6"></canvas>
</div>
</div>
```
```
/* xxx.css */
.container{
flex-direction: column;
background-color: #F1F3F5;
align-items: center;
}
canvas{
width: 600px;
height: 300px;
margin-bottom: 100px;
background-color: #fdfdfd;
border: 5px solid red;
}
.content{
width: 80%;
margin-top: 50px;
margin-bottom: 50px;
display: flex;
flex-wrap: wrap;
justify-content: space-around;
}
text{
font-size: 35px;
width: 200px;
height: 80px;
color: white;
border-radius: 20px;
text-align: center;
background-color: #6060e7;
margin-bottom: 30px;
}
```
```
// xxx.js
import prompt from '@system.prompt';
export default {
data:{
compositeOperation: 'source-over'
},
onShow(){
let ctx = this.$refs.canvas0.getContext("2d");
// Create an image object.
let img = new Image();
// Set the image path.
img.src = 'common/images/2.png';
// Set the image width.
img.width= 150;
// Set the image height.
img.height=150;
// Create an image tiling container.
var pat = ctx.createPattern(img, 'repeat');
ctx.fillStyle = pat;
ctx.fillRect(0, 0, 600, 300);
},
change(){
// Obtain the brush after the canvas is created.
let ctx = this.$refs.canvas1.getContext("2d");
ctx.clearRect(0,0,600,1000);
if(this.compositeOperation == "source-over"){
this.compositeOperation = "destination-over";
}else{
this.compositeOperation = "source-over";
}
ctx.globalCompositeOperation = this.compositeOperation;
let img = new Image();
img.src = 'common/images/2.png';
// Invoked when the image is successfully obtained.
img.onload = function() {
ctx.drawImage(img, 150, 20, 200, 200);
};
let img1 = new Image();
img1.src = 'common/images/3.png';
img1.onload = function() {
// Draw an image.
ctx.drawImage(img1, 250, 80, 200, 200);
};
// A method is triggered when the image fails to be obtained.
img1.onerror = function() {
prompt.showToast({message:"error",duration:2000})
};
},
rotate(){
let ctx = this.$refs.canvas2.getContext("2d");
ctx.clearRect(0,0,600,300);
// Rotate the image.
ctx.rotate(10 * Math.PI / 180);
let img = new Image();
img.src = 'common/images/2.png';
img.onload = function() {
ctx.drawImage(img, 300, 0, 100, 100);
};
},
scale(){
let ctx = this.$refs.canvas3.getContext("2d");
ctx.clearRect(0,0,600,200);
// Scale the image.
ctx.scale(1.3,1.2);
let img = new Image();
img.src = 'common/images/2.png';
img.onload = function() {
ctx.drawImage(img, 0, 0, 50, 50);
};
},
translate(){
let ctx = this.$refs.canvas4.getContext("2d");
ctx.clearRect(0,0,600,300);
ctx.translate(10,0);
let img = new Image();
img.src = 'common/images/2.png';
img.onload = function() {
ctx.drawImage(img, 0, 50, 300, 200);
};
},
transform(){
let ctx = this.$refs.canvas5.getContext("2d");
ctx.clearRect(0,0,600,300);
ctx.transform(1.1, 0.1, 0.1, 1, 10, 0);
let img = new Image();
img.src = 'common/images/2.png';
img.onload = function() {
ctx.drawImage(img, 0, 50, 100, 100);
};
},
setTransform(){
let ctx = this.$refs.canvas6.getContext("2d");
ctx.clearRect(0,0,600,300);
ctx.setTransform(1.1, 0.1, 0.1, 1, 10, 0);
let img = new Image();
img.src = 'common/images/2.png';
img.onload = function() {
ctx.drawImage(img, 0, 50, 100, 100);
};
},
}
```
![en-us_image_0000001232003008](figures/en-us_image_0000001232003008.gif)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> - Unlike the **transform()** function, the **setTransform()** function resets the existing transformation matrix and creates a transformation matrix even if it uses the same parameters.
>
> - The following formulas calculate coordinates of the transformed graph. **x** and **y** represent coordinates before transformation, and **x'** and **y'** represent coordinates after transformation.
> x' = scaleX \* x + skewY \* y + translateX
>
> y' = skewX \* x + scaleY \* y + translateY
## Adding Methods
Use the **save** method to save the brush style, and use the **restore** method to restore the saved settings. In the following example, set the brush to red. After the brush setting is saved, clear the canvas and change the brush to blue. In this moment, directly using the brush will get a blue rectangle; using the brush after the restore operation will get a red rectangle.
```
<!-- xxx.hml -->
<div class="container">
<div class="content">
<canvas ref="canvas"></canvas>
</div>
<div class="content">
<text onclick="save">save</text>
<text onclick="clear">clear</text>
<text onclick="restore">restore</text>
</div>
</div>
```
```
/* xxx.css */
.container{
flex-direction: column;
background-color: #F1F3F5;
align-items: center;
}
canvas{
margin-top: 300px;
width: 600px;
height: 500px;
background-color: #fdfdfd;
border: 5px solid red;
}
.content{
width: 80%;
margin-top: 50px;
margin-bottom: 50px;
display: flex;
flex-wrap: wrap;
justify-content: space-around;
}
text{
width: 150px;
height: 80px;
color: white;
border-radius: 20px;
text-align: center;
background-color: #6060e7;
margin-bottom: 30px;
}
```
```
// xxx.js
import prompt from '@system.prompt';
export default {
data:{
ctx: '',
},
onShow(){
this.ctx = this.$refs.canvas.getContext("2d");
this.ctx.fillStyle = "red"
this.ctx.fillRect(200, 150, 200, 200);
},
save(){
// Save the brush setting.
this.ctx.save();
prompt.showToast({message:"save succeed"});
},
clear(){
this.ctx.clearRect(0,0,600,500);
// Change the brush color.
this.ctx.fillStyle = "#2133d2";
},
restore(){
this.ctx.beginPath();
// Restore the brush setting.
this.ctx.restore();
this.ctx.fillRect(200, 150, 200, 200);
},
}
```
![en-us_image_0000001231683144](figures/en-us_image_0000001231683144.gif)
# &lt;chart&gt; Development
The **&lt;chart&gt;** component displays line charts, gauge charts, and bar charts. For details, see [chart](../reference/arkui-js/js-components-basic-chart.md).
## Creating a &lt;chart&gt; Component
Create a **&lt;chart&gt;** component in the .hml file under **pages/index**.
```
<!-- xxx.hml -->
<div class="container">
<chart class="chart-data" type="line" options="{{lineOps}}" datasets="{{lineData}}"></chart>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
.chart-data {
width: 700px;
height: 600px;
}
```
```
/* xxx.js */
export default {
data: {
lineData: [
{
data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628, 791, 505, 613, 575, 475, 553, 491, 680, 657, 716]
}
],
lineOps: {
xAxis: {
min: 0,
max: 20,
display: false,
},
yAxis: {
min: 0,
max: 1000,
display: false,
},
series: {
lineStyle: {
width: 15,
},
}
},
}
}
```
![en-us_image_0000001231683156](figures/en-us_image_0000001231683156.png)
## Setting the Chart Type
Define the chart type using the **type** attribute, for example, setting a chart to a bar chart.
```
<!-- xxx.hml -->
<div class="container">
<div class="container">
<div class="switch-block">
<text class="title">
{{ title }}
</text>
</div>
<tabs class="tabs" index="0" vertical="false" onchange="changes">
<tab-content class="tabcontent" scrollable="true">
<tabs >
<tab-bar class="tab-bar" mode="fixed"style="margin-bottom: 50px;">
<text class="tab-text">Line chart</text>
<text class="tab-text">Bar chart</text>
<text class="tab-text">Gauge chart</text>
</tab-bar>
<tab-content>
<div class="bar-block" style="margin-left: 30px;">
<chart class="chart-data"type="line" ref="linechart" options="{{ lineOps }}" datasets="{{ lineData }}">
</chart>
</div>
<div class="bar-block">
<chart class="data-bar"type="bar" id="bar-chart" options="{{ barOps }}" datasets="{{ barData }}">
</chart>
</div>
<div class="chart-block">
<chart type="gauge" ></chart>
</div>
</tab-content>
</tabs>
</tab-content>
</tabs>
</div>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
justify-content: center;
background-color: #F1F3F5;
}
.chart-data {
width: 700px;
height: 600px;
}
.title{
margin-left: 50px;
margin-top: 50px;
font-size: 50px;
}
.line-block{
align-items: center;
justify-content: center;
}
.bar-block{
align-items: center;
justify-content: center;
}
.chart-block{
width: 90%;
margin-left: 30px;
}
```
```
/* xxx.js */
export default {
data: {
title:"Type display",
barData: [
{
fillColor: '#3848e8',
data: [763, 550, 551, 554, 731, 654, 525, 696, 595],
}
],
lineData: [
{
strokeColor: '#0081ff',
fillColor: '#cce5ff',
data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628, 791, 505, 613, 575, 475, 553, 491, 680, 657, 716],
gradient: true,
}
],
lineOps: {
xAxis: {
min: 0,
max: 20,
display: false,
},
yAxis: {
min: 0,
max: 1000,
display: false,
},
series:{
lineStyle: {
width: "5px",
smooth: true,
},
headPoint: {
shape:"circle",
size: 20,
strokeWidth: 5,
fillColor: '#ffffff',
strokeColor: '#007aff',
display: true,
},
loop:{
margin: 2,
gradient: true
}
},
},
barOps: {
xAxis: {
min: 0,
max: 20,
display: false,
axisTick: 10,
},
yAxis: {
min: 0,
max: 1000,
},
},
},
}
```
![en-us_image_0000001275803181](figures/en-us_image_0000001275803181.gif)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> The **&lt;chart&gt;** component does not display the value of each point.
## Setting the Chart Attributes
In the **options** attribute of the **&lt;chart&gt;** component, you can set the x-axis, y-axis, and data series parameters. In the **datasets** attribute, you can set the line color, fill color, gradient fill color, and drawing point set.
```
<!-- xxx.hml -->
<div class="container">
<chart class="chart-data" type="line" options="{{lineOps}}" datasets="{{lineData}}"></chart>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
.chart-data {
width: 700px;
height: 600px;
}
```
```
/* xxx.js */
export default {
data: {
// Line chart data
lineData: [
{
strokeColor: '#0081ff',
fillColor: '#cce5ff', // Fill color
data: [463, 250, 251, 254, 431, 354, 225, 396, 295, 328, 491, 205, 313, 275, 475, 553, 491, 380, 357, 416],
gradient: true,
}
],
lineOps: {
// X-axis parameters
xAxis: {
min: 0,
max: 20,
display: false,
},
// Y-axis parameters
yAxis: {
min: 0,
max: 1000,
display: false,
},
// Data series parameters
series: {
// Line style
lineStyle: {
width: "5px",
smooth: true,
},
// Style and size of the white point at the start of the line
headPoint: {
shape: "circle",
size: 20,
strokeWidth: 5,
fillColor: '#ffffff',
strokeColor: '#007aff',
display: true,
},
// Whether to start drawing again when the screen is looped.
loop: {
margin: 2,
gradient: true
}
}
},
},
}
```
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> - The **options** attribute supports the settings of bar charts and line charts but does not support those of gauge charts.
>
> - The **datasets** attribute supports the datasets for bar charts and line charts but does not support those of gauge charts.
>
> - Only line charts support **series**.
## Adding Data
Use the **append** method of the **&lt;chart&gt;** component to dynamically add data.
```
<!-- xxx.hml -->
<div class="container">
<stack class="chart-region">
<chart class="chart-data" type="line" ref="linechart" options="{{lineOps}}" datasets="{{lineData}}"></chart>
</stack>
<button value="Add data"onclick="addData"></button>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
.chart-region {
height: 400px;
width: 700px;
}
.chart-data {
width: 700px;
height: 600px;
}
button {
width: 100%;
height: 50px;
background-color: #F4F2F1;
text-color: #0C81F3;
margin-top: 30px;
}
```
```
// xxx.js
export default {
data: {
lineData: [
{
strokeColor: '#de0b6e',
fillColor: '#bb09a3',
data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628, 791, 505, 613, 575, 475, 553, 491, 680, 657, 716],
gradient: true,
}
],
lineOps: {
xAxis: {
min: 0,
max: 20,
display: false,
},
yAxis: {
min: 0,
max: 1000,
display: false,
},
series: {
lineStyle: {
width: "5px",
smooth: true,
},
headPoint: {
shape: "circle",
size: 20,
strokeWidth: 5,
fillColor: '#ffffff',
strokeColor: '#f8145c',
display: true,
},
loop: {
margin: 2,
gradient: true,
}
}
},
},
addData() {
this.$refs.linechart.append({
serial: 0,
data: [Math.floor(Math.random() * 400) + 200]
})
}
}
```
![en-us_image_0000001275803177](figures/en-us_image_0000001275803177.gif)
## Example Scenario
Select the data display status using **&lt;switch&gt;**. When **&lt;switch&gt;** is set to **true**, the timer is used to dynamically display data.
```
<!-- xxx.hml -->
<div class="container">
<div class="container">
<div class="switch-block">
<text class="title">{{ title }} </text>
<switch class="switch" showtext="{{ showText }}" allow-scale="{{ allowScale }}"onchange="change">
</switch>
</div>
<tabs class="tabs" index="0" vertical="false" onchange="changes">
<tab-content class="tabcontent" scrollable="true">
<div>
<tabs class="tabs" index="0" vertical="false" onchange="changes">
<tab-content class="tabcontent" scrollable="true">
<div class="line-class">
<div class="bar-block">
<chart class="chart-data" type="line" ref="linechart" options="{{ lineOps }}"
datasets="{{ lineData }}">
</chart>
</div>
<div class="bar-block">
<chart class="data-bar" type="bar" id="bar-chart" options="{{ barOps }}"datasets="{{ barData }}">
</chart>
</div>
</div>
</tab-content>
</tabs>
</div>
<div>
<div class="container">
<list class="todo-wrapper">
<list-item for="{{ barData }}" class="todo-item">
<text class="todo-title">{{ $item.data }}</text>
</list-item>
</list>
<list class="todo-wrapper">
<list-item for="{{ lineData.data }}" class="todo-item">
<text class="todo-title">{{ $item.value }}</text>
</list-item>
</list>
</div>
</div>
</tab-content>
</tabs>
</div>
</div>
```
```
/* xxx.css */
.container{
display:flex;
flex-direction:column;
background-color: #F1F3F5;
}
.line-class{
display: flex;
flex-direction: column;
}
.title{
font-size: 40px;
margin-left: 40px;
}
.switch-block {
margin-top: 30px;
width: 98%;
height: 80px;
display: flex;
justify-content: space-between;
}
.switch{
font-size: 40px;
}
.bar-block {
margin-top: 80px;
margin-left: 40px;
position: relative;
width: 90%;
border-radius: 10px;
background-color: #25FAB27B;
height: 40%;
justify-content: center;
}
```
```
// xxx.js
export default {
data: {
interval: null,
title: "Data Display",
allowScale: true,
dataLength: 30,
barGroup: 3,
lineData: null,
lineOps: {
xAxis: {
min: 0,
max: 5
},
yAxis: {
min: 0,
max: 100
},
series: {
lineStyle: {
width: '1px',
},
headPoint: {
shape: 'circle',
size: 10,
strokeWidth: 2,
fillColor: '#ffffff',
strokeColor: '#8477DF'
},
loop: {
margin: 2
}
}
},
barData: [
{
fillColor: '#97CF0A2C',
data: [20, 20,40, 56]
},
{
fillColor: '#6D0A7ACF',
data: [52, 40, 2, 67]
},
{
fillColor: '#6A0ACFA1',
data: [56, 2, 77, 40]
}
],
barOps: {
xAxis: {
min: 0,
max: 20,
axisTick: 5
},
yAxis: {
min: 0,
max: 100
}
}
},
onInit() {
this.changeLine();
},
change(e) {
if (e.checked) {
this.interval = setInterval(() => {
this.changeLine();
this.changeBar();
}, 1000)
} else {
clearInterval(this.interval);
}
},
changeLine() {
var dataArray = [];
for (var i = 0; i < this.dataLength; i++) {
var nowValue = Math.floor(Math.random() * 99 + 1);
var obj = {
"value": nowValue,
"description": nowValue + "",
"textLocation": "top",
"textColor": "#CDCACA",
"pointStyle": {
"shape": "circle",
"size": 5,
"fillColor": "#CF0A2C",
"strokeColor": "#CF0A2C"
}
};
dataArray.push(obj);
}
this.lineData = [
{
strokeColor: '#0081ff',
fillColor: '#FF07CDC4',
data: dataArray,
gradient: true,
}
]
},
changeBar() {
for (var i = 0;i < this.barGroup; i++) {
var dataArray = this.barData[i].data;
for (var j = 0;j < 4; j++) {
dataArray[j] = Math.floor(Math.random() * 99 + 1);
}
}
this.barData = this.barData.splice(0, this.barGroup + 1);
},
changes(e) {
console.log("Tab index: " + e.index);
},
}
```
![en-us_image_0000001232162328](figures/en-us_image_0000001232162328.gif)
# &lt;dialog&gt; Development # &lt;dialog&gt; Development
The &lt;dialog&gt; component is custom pop-up container for showing critical information or calling for an action. For details, see [dialog](../reference/arkui-js/js-components-container-dialog.md). The **&lt;dialog&gt;** component is custom pop-up container for showing critical information or calling for an action. For details, see [dialog](../reference/arkui-js/js-components-container-dialog.md).
## Creating a &lt;dialog&gt; Component ## Creating a &lt;dialog&gt; Component
Create a &lt;dialog&gt; component in the .hml file under pages/index and add &lt;button&gt; components to trigger the &lt;dialog&gt;. The &lt;dialog&gt; component supports only the width, height, margin, margin-[left|top|right|bottom], and margin-[start|end] styles. Create a **&lt;dialog&gt;** component in the .hml file under **pages/index** and add **&lt;button&gt;** components to trigger the **&lt;dialog&gt;**. The **&lt;dialog&gt;** component supports only the **width**, **height**, **margin**, **margin-[left|top|right|bottom]**, and **margin-[start|end]** styles.
``` ```
<!-- xxx.hml --> <!-- xxx.hml -->
<div class="doc-page"> <div class="doc-page">
<dialog class="dialogClass" id="dialogId"><div class="content"> <dialog class="dialogClass" id="dialogId">
<div class="content" dragable="true">
<text>this is a dialog</text> <text>this is a dialog</text>
</div> </div>
</dialog> </dialog>
<button value="click me" onclick="openDialog"></button> <button value="click me" onclick="openDialog"></button>
</div> </div>
``` ```
...@@ -23,6 +24,8 @@ The &lt;dialog&gt; component is custom pop-up container for showing critical inf ...@@ -23,6 +24,8 @@ The &lt;dialog&gt; component is custom pop-up container for showing critical inf
``` ```
/* xxx.css */ /* xxx.css */
.doc-page { .doc-page {
width: 100%;
height: 100%;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
...@@ -67,7 +70,9 @@ export default { ...@@ -67,7 +70,9 @@ export default {
## Setting Dialog Box Response ## Setting Dialog Box Response
Add a cancel event that is triggered when a user touches a non-dialog area to cancel the pop-up dialog box. Add the show and close methods to display and close the dialog box, respectively. Add a **cancel** event that is triggered when a user touches a non-dialog area to cancel the pop-up dialog box. Add the **show** and **close** methods to display and close the dialog box, respectively.
``` ```
<!-- xxx.hml --> <!-- xxx.hml -->
...@@ -82,9 +87,13 @@ Add a cancel event that is triggered when a user touches a non-dialog area to ca ...@@ -82,9 +87,13 @@ Add a cancel event that is triggered when a user touches a non-dialog area to ca
</div> </div>
``` ```
``` ```
/* xxx.css */ /* xxx.css */
.doc-page { .doc-page {
width: 100%;
height: 100%;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
...@@ -113,6 +122,8 @@ button{ ...@@ -113,6 +122,8 @@ button{
} }
``` ```
``` ```
/* xxx.js */ /* xxx.js */
import prompt from '@system.prompt'; import prompt from '@system.prompt';
...@@ -133,18 +144,20 @@ export default { ...@@ -133,18 +144,20 @@ export default {
![en-us_image_0000001223287720](figures/en-us_image_0000001223287720.gif) ![en-us_image_0000001223287720](figures/en-us_image_0000001223287720.gif)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> - This component supports only one child component. > - This component supports only one child component.
> >
> - Attributes and styles of a &lt;dialog&gt; component cannot be dynamically updated. > - Attributes and styles of a **&lt;dialog&gt;** component cannot be dynamically updated.
> >
> - The &lt;dialog&gt; component does not support the focusable and click-effect attributes. > - The **&lt;dialog&gt;** component does not support the **focusable** and **click-effect** attributes.
## Example Scenario ## Example Scenario
Use the &lt;dialog&gt; component to implement a schedule. When the dialog box is open, use the [&lt;textarea&gt;](../reference/arkui-js/js-components-basic-textarea.md) component to add an event and touch the OK button to obtain the current time and save the input text. The events in the calendar are displayed in a list. Use the **&lt;dialog&gt;** component to implement a schedule. When the dialog box is open, use the [**&lt;textarea&gt;**](../reference/arkui-js/js-components-basic-textarea.md) component to add an event and touch the OK button to obtain the current time and save the input text. The events in the calendar are displayed in a list.
``` ```
<!-- xxx.hml --> <!-- xxx.hml -->
...@@ -180,6 +193,8 @@ Use the &lt;dialog&gt; component to implement a schedule. When the dialog box is ...@@ -180,6 +193,8 @@ Use the &lt;dialog&gt; component to implement a schedule. When the dialog box is
</div> </div>
``` ```
``` ```
/* xxx.css */ /* xxx.css */
.doc-page { .doc-page {
...@@ -248,6 +263,8 @@ Use the &lt;dialog&gt; component to implement a schedule. When the dialog box is ...@@ -248,6 +263,8 @@ Use the &lt;dialog&gt; component to implement a schedule. When the dialog box is
} }
``` ```
``` ```
/* xxx.js */ /* xxx.js */
var info = null; var info = null;
......
# &lt;form&gt; Development # &lt;form&gt; Development
The &lt;form&gt; component allows the content in [&lt;input&gt;](../reference/arkui-js/js-components-basic-input.md)components to be submitted and reset. For details, see [form](../reference/arkui-js/js-components-container-form.md). The &lt;form&gt; component allows the content in [&lt;input&gt;](../reference/arkui-js/js-components-basic-input.md) components to be submitted and reset. For details, see [form](../reference/arkui-js/js-components-container-form.md).
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> This component is supported since API version 6. > This component is supported since API version 6.
## Creating a &lt;form&gt; Component ## Creating a &lt;form&gt; Component
Create a &lt;form&gt; component in the .hml file under pages/index. Create a **&lt;form&gt;** component in the .hml file under **pages/index**.
``` ```
<!-- xxx.hml --> <!-- xxx.hml -->
<div class="container"> <div class="container">
<form> <input type="text" style="width:80%"></input> <form> <input type="text" style="width:80%"></input>
</form> </form>
</div> </div>
``` ```
...@@ -24,6 +24,8 @@ The &lt;form&gt; component allows the content in [&lt;input&gt;](../reference/ar ...@@ -24,6 +24,8 @@ The &lt;form&gt; component allows the content in [&lt;input&gt;](../reference/ar
``` ```
/* xxx.css */ /* xxx.css */
.container { .container {
width: 100%;
height: 100%;
flex-direction: column; flex-direction: column;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
...@@ -36,7 +38,7 @@ The &lt;form&gt; component allows the content in [&lt;input&gt;](../reference/ar ...@@ -36,7 +38,7 @@ The &lt;form&gt; component allows the content in [&lt;input&gt;](../reference/ar
## Zooming In or Out on a Form ## Zooming In or Out on a Form
To implement the zoom effect after a form is clicked, add the click-effect attribute to the &lt;form&gt; component. For values of click-effect, see [Universal Attributes](../reference/arkui-js/js-components-common-attributes.md). To implement the zoom effect after a form is clicked, add the **click-effect** attribute to the **&lt;form&gt;** component. For values of **click-effect**, see [Universal Attributes](../reference/arkui-js/js-components-common-attributes.md).
``` ```
<!-- xxx.hml --> <!-- xxx.hml -->
...@@ -48,10 +50,23 @@ The &lt;form&gt; component allows the content in [&lt;input&gt;](../reference/ar ...@@ -48,10 +50,23 @@ The &lt;form&gt; component allows the content in [&lt;input&gt;](../reference/ar
``` ```
## Setting the Form Style ## Setting Form Styles
Add the **background-color** and **border** attributes.
```
<!-- xxx.hml -->
<div class="container">
<form id="formId" class="formClass" click-effect="spring-large">
<input type="text"></input>
</form>
</div>
```
Add the background-color and border attributes.
``` ```
/* xxx.css */ /* xxx.css */
...@@ -63,8 +78,7 @@ Add the background-color and border attributes. ...@@ -63,8 +78,7 @@ Add the background-color and border attributes.
} }
.formClass{ .formClass{
width: 80%; width: 80%;
padding: 10px; height: 20%;
border: 1px solid #c3d3e7;
} }
``` ```
...@@ -74,24 +88,24 @@ Add the background-color and border attributes. ...@@ -74,24 +88,24 @@ Add the background-color and border attributes.
## Adding Response Events ## Adding Response Events
To submit or reset a form, add the submit and reset events. To submit or reset a form, add the **submit** and **reset** events.
``` ```
<!-- xxx.hml --> <!-- xxx.hml -->
<div class="container" style="background-color:#F1F3F5;"> <div class="container">
<form onsubmit='onSubmit' onreset='onReset' style="justify-content: center; align-items: center;text-align: center;"> <form onsubmit='onSubmit' onreset='onReset' class="form">
<div style="flex-direction: column;justify-content: center;align-self: center;">
<div style="justify-content: center; align-items: center;"> <div style="justify-content: center; width: 100%;">
<label>Option 1</label> <label>Option 1</label>
<input type='radio' name='radioGroup' value='radio1'></input> <input type='radio' name='radioGroup' value='radio1'></input>
<label>Option 2</label> <label>Option 2</label>
<input type='radio' name='radioGroup' value='radio2'></input> <input type='radio' name='radioGroup' value='radio2'></input>
</div> </div>
<div style="margin-top: 30px;justify-content: center; align-items: center;"> <div style="margin-top: 30px;justify-content: center; align-items: center;">
<input type="submit" value="Submit" style="width:100px; margin-right:20px;" ></input> <input type="submit" value="Submit" style="width:100px; margin-right:20px;" ></input>
<input type="reset" value="Reset" style="width:100px;"></input> <input type="reset" value="Reset" style="width:100px;"></input>
</div> </div>
</div>
</form> </form>
</div> </div>
``` ```
...@@ -122,7 +136,7 @@ export default{ ...@@ -122,7 +136,7 @@ export default{
Select an option and submit or reset the form data. Select an option and submit or reset the form data.
Create [&lt;input&gt;](../reference/arkui-js/js-components-basic-input.md) (en-us_topic_0000001173324647.xml) components, set their type attribute to checkbox and radio, and use the onsubmit and onreset events of the &lt;form&gt; component to submit and reset the form data. Create [&lt;input&gt;](../reference/arkui-js/js-components-basic-input.md) components, set their **type** attribute to **checkbox** and **radio**, and use the **onsubmit** and **onreset** events of the **&lt;form&gt;** component to submit and reset the form data.
``` ```
......
# &lt;image-animator&gt; Development
The **&lt;image-animator&gt;** component applies an animation to images. For details, see [image-animator](../reference/arkui-js/js-components-basic-image-animator.md).
## Creating an &lt;image-animator&gt; Component
In the **pages/index** directory, create an **&lt;image-animator&gt;** component in the .hml file, define the component style in the .css file, and reference an image in the .js file.
```
<!-- xxx.hml -->
<div class="container">
<image-animator class="animator" images="{{frames}}" duration="3s"/>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
.animator {
width: 500px;
height: 500px;
}
```
```
/* index.js */
export default {
data: {
frames: [
{
src: "/common/landscape1.jpg",
},
{
src: "/common/landscape2.jpg",
}
],
},
};
```
![en-us_image_0000001275922969](figures/en-us_image_0000001275922969.gif)
## Setting the &lt;image-animator&gt; Attributes
Add the **iteration** (number of times the animation is played), **reverse** (whether the animation plays backward), **fixedsize** (whether the image size is fixed to the component size), **duration** (duration of the animation), and **fillmode** (style of the target when the animation is not playing) attributes.
```
<!-- xxx.hml -->
<div class="container">
<image-animator class="animator" fixedsize="false" iteration='2' reverse="false" ref="animator" fillmode="none" images="{{frames}}"duration="5s" />
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
background-color: #F1F3F5;
}
.animator {
width: 500px;
height: 500px;
}
```
```
/* index.js */
export default {
data: {
frames: [
{
src: 'common/landscape1.jpg',
width: '250px',
height: '250px',
left: '150px',
top: '50px',
},
{
src: 'common/landscape2.jpg',
width: '300px',
height: '300px',
left: '150px',
top: '100px',
},
{
src: 'common/landscape1.jpg',
width: '350px',
height: '350px',
left: '150px',
top: '150px',
},
{
src: 'common/landscape2.jpg',
width: '400px',
height: '400px',
left: '150px',
top: '200px',
},
{
src: 'common/landscape3.jpg',
width: '450px',
height: '450px',
left: '150px',
top: '250px',
},
{
src: 'common/landscape4.jpg',
width: '500px',
height: '500px',
left: '150px',
top: '300px',
},
],
},
};
```
![en-us_image_0000001276003481](figures/en-us_image_0000001276003481.gif)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> - If the **duration** attribute is set in the **images** attribute, the **duration** attribute set in the **&lt;image-animator&gt;** component is invalid.
>
> - If **fixedsize** is set to **true**, the **width**, **height**, **top**, and **left** settings in **images** will not take effect.
>
> - Setting **reverse** to **false** indicates that images are played from the first one to the last one. Setting **reverse** to **true** indicates that images are played from the last one to the first one.
## Binding Events
Add the start, pause, stop, and resume events to the **&lt;image-animator&gt;** component. Specifically, the start event is triggered when the image animator starts playing; the pause event is triggered when the image animator is clicked; the resume event is triggered when the image animator is pressed and held; the stop event is triggered when the image animator stops playing.
```
<!-- xxx.hml -->
<div class="doc-page">
<image-animator class="img" id="img" images="{{imginfo}}" iteration="1" duration="10s" onstart="popstart" onpause="poppause"
onstop="popstop" onresume="popresume" onlongpress="setresume" onclick="setpause">
</image-animator>
</div>
```
```
/* xxx.css */
.doc-page {
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: #F1F3F5;
}
.img {
width: 600px;
height: 600px;
border: 3px solid orange;
}
```
```
/* index.js */
import prompt from '@system.prompt';
export default {
data: {
imginfo: [
{
src: 'common/landscape1.jpg',
},{
src: 'common/landscape2.jpg',
},{
src: 'common/landscape3.jpg',
},{
src: 'common/landscape4.jpg',
}
],
},
onInit() {
},
setpause(e) {
this.$element('img').pause()
},
setresume(e) {
this.$element('img').resume()
},
popstart(e) {
prompt.showToast({
message: 'Started.'
})
},
poppause(e) {
prompt.showToast({
message: 'Paused.'
})
},
popstop(e) {
prompt.showToast({
message: 'Stopped.'
})
},
popresume(e) {
prompt.showToast({
message: 'Resumed.'
})
}
}
```
![en-us_image_0000001231843076](figures/en-us_image_0000001231843076.gif)
## Example Scenario
You can click the start or stop button to change the image animation status.
Call the start, pause, stop, and resume methods to start, pause, stop, and resume the image animation, and call the **getState** method to check the image animation status.
```
<!-- xxx.hml -->
<div class="doc-page">
<image-animator class="img" id="img" images="{{imginfo}}" iteration="2" reverse="{{rev}}" duration="10s">
</image-animator>
<div style="width: 700px;height:450px;margin-top: 40px;flex-direction:column;justify-content:space-around;">
<div class="container">
<button type="capsule" value="Start" onclick="startimg"></button>
<button type="capsule" value="Pause" onclick="pauseimg"></button>
</div>
<div class="container">
<button type="capsule" value="Stop" onclick="stopimg"></button>
<button type="capsule" value="Resume" onclick="resumeimg"></button>
</div>
<div class="container">
<button type="capsule" value="Get Status" onclick="getimgstate"></button>
<button type="capsule" value="{{revVal}}" onclick="revimg"></button>
</div>
</div>
</div>
```
```
/* xxx.css */
.doc-page {
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: #F1F3F5;
}
.img {
width: 600px;
height: 600px;
border: 3px solid orange;
}
button{
width: 260px
}
.container {
width: 100%;
height: 120px;
align-items: center;
justify-content: space-around;
}
```
```
/* index.js */
import prompt from '@system.prompt';
export default {
data: {
rev:false,
imginfo: [
{
src: 'common/landscape1.jpg',
},{
src: 'common/landscape2.jpg',
},{
src: 'common/landscape3.jpg',
},{
src: 'common/landscape4.jpg',
}
],
revVal:'Reverse'
},
onInit() {
},
startimg(e) {
this.$element('img').start()
},
pauseimg(e) {
this.$element('img').pause()
},
stopimg(e) {
this.$element('img').stop()
},
resumeimg(e) {
this.$element('img').resume()
},
getimgstate(e) {
prompt.showToast({
message: 'Current state:' + this.$element('img').getState()
})
},
revimg(e) {
this.rev = !this.rev
if (this.rev) {
this.revVal ='Play Forward'
} else {
this.revVal ='Reverse'
}
}
}
```
![en-us_image_0000001276162717](figures/en-us_image_0000001276162717.gif)
# &lt;image&gt; Development # &lt;image&gt; Development
The &lt;image&gt; component is used to render and display images. For details, see [image](../reference/arkui-js/js-components-basic-image.md). The **&lt;image&gt;** component is used to render and display images. For details, see [image](../reference/arkui-js/js-components-basic-image.md).
## Creating an &lt;image&gt; Component ## Creating an &lt;image&gt; Component
Create an &lt;image&gt; component in the .hml file under pages/index. Create an **&lt;image&gt;** component in the .hml file under **pages/index**.
``` ```
<!-- index.hml --> <!-- index.hml -->
<div class="container"> <div class="container">
<image src="common/images/bg-tv.jpg"> </image> <image style="height: 30%;" src="common/images/bg-tv.jpg"> </image>
</div> </div>
``` ```
...@@ -19,6 +19,8 @@ The &lt;image&gt; component is used to render and display images. For details, s ...@@ -19,6 +19,8 @@ The &lt;image&gt; component is used to render and display images. For details, s
``` ```
/* xxx.css */ /* xxx.css */
.container { .container {
width: 100%;
height: 100%;
flex-direction: column; flex-direction: column;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
...@@ -31,7 +33,9 @@ The &lt;image&gt; component is used to render and display images. For details, s ...@@ -31,7 +33,9 @@ The &lt;image&gt; component is used to render and display images. For details, s
## Setting the Image Style ## Setting the Image Style
Set the width, height, and object-fit attributes to define the width, height, and scale type of an image. Set the **width**, **height**, and **object-fit** attributes to define the width, height, and scale type of an image.
``` ```
<!-- index.hml --> <!-- index.hml -->
...@@ -40,31 +44,37 @@ Set the width, height, and object-fit attributes to define the width, height, an ...@@ -40,31 +44,37 @@ Set the width, height, and object-fit attributes to define the width, height, an
</div> </div>
``` ```
``` ```
/* xxx.css */ /* xxx.css */
.container { .container {
width: 100%;
height: 100%;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
background-color:#F1F3F5; background-color:#F1F3F5;
} }
image{ image{
width: 80%; height: 500px; width: 80%;
height: 500px;
border: 5px solid saddlebrown; border: 5px solid saddlebrown;
border-radius: 20px; border-radius: 20px;
object-fit: contain; object-fit: contain;
match-text-direction:true; match-text-direction:true;
} }
``` ```
![en-us_image_0000001222807796](figures/en-us_image_0000001222807796.png) ![en-us_image_0000001222807796](figures/en-us_image_0000001222807796.png)
## Loading Images ## Loading Images
When an image is successfully loaded, the complete event is triggered, and the loaded image is returned. If an exception occurs during image loading, the error event is triggered, and the image loading failure is printed. When an image is successfully loaded, the **complete** event is triggered, and the loaded image is returned. If an exception occurs during image loading, the **error** event is triggered, and the image loading failure is printed.
``` ```
...@@ -83,6 +93,8 @@ When an image is successfully loaded, the complete event is triggered, and the l ...@@ -83,6 +93,8 @@ When an image is successfully loaded, the complete event is triggered, and the l
``` ```
/* xxx.css */ /* xxx.css */
.container{ .container{
width: 100%;
height: 100%;
flex-direction: column; flex-direction: column;
justify-content: center; justify-content: center;
align-self: center; align-self: center;
...@@ -123,7 +135,7 @@ export default { ...@@ -123,7 +135,7 @@ export default {
## Example Scenario ## Example Scenario
In this example you touch and hold an image to gradually hide it. After the image is completely hidden, it will show in its original setting. Set a setInterval timer to change the image opacity at a specified interval so that it is hidden gradually. When the opacity changes to 0, the timer is cleared and the opacity is set to 1. In this example you touch and hold an image to gradually hide it. After the image is completely hidden, it will show in its original setting. Set a **setInterval** timer to change the image opacity at a specified interval so that it is hidden gradually. When the opacity changes to **0**, the timer is cleared and the opacity is set to **1**.
``` ```
<!-- index.hml --> <!-- index.hml -->
...@@ -143,6 +155,8 @@ export default { ...@@ -143,6 +155,8 @@ export default {
``` ```
/* xxx.css */ /* xxx.css */
.page-container { .page-container {
width: 100%;
height: 100%;
flex-direction:column; flex-direction:column;
align-self: center; align-self: center;
justify-content: center; justify-content: center;
......
# <input> Development # &lt;input&gt; Development
The <input> component provides an interactive way to receive user input of various types, including date, checkbox, and button. For details, see [input](../reference/arkui-js/js-components-basic-input.md). The **&lt;input&gt;** component provides an interactive way to receive user input of various types, including **date**, **checkbox**, and **button**. For details, see [input](../reference/arkui-js/js-components-basic-input.md).
## Creating an <input> Component ## Creating an &lt;input&gt; Component
Create an <input> component in the .hml file under pages/index. Create an **&lt;input&gt;** component in the .hml file under **pages/index**.
``` ```
<!-- xxx.hml --> <!-- xxx.hml -->
<div class="container"> <div class="container">
<input type="text"> Please enter the content </input> <input type="text">
Please enter the content
</input>
</div> </div>
``` ```
...@@ -20,6 +22,8 @@ Create an <input> component in the .hml file under pages/index. ...@@ -20,6 +22,8 @@ Create an <input> component in the .hml file under pages/index.
``` ```
/* xxx.css */ /* xxx.css */
.container { .container {
width: 100%;
height: 100%;
flex-direction: column; flex-direction: column;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
...@@ -32,7 +36,7 @@ Create an <input> component in the .hml file under pages/index. ...@@ -32,7 +36,7 @@ Create an <input> component in the .hml file under pages/index.
## Setting the Input Type ## Setting the Input Type
Set the type attribute of the <input> component to button, date, or any of the supported values. Set the **type** attribute of the **&lt;input&gt;** component to **button**, **date**, or any of the supported values.
``` ```
...@@ -59,6 +63,8 @@ Set the type attribute of the <input> component to button, date, or any of the s ...@@ -59,6 +63,8 @@ Set the type attribute of the <input> component to button, date, or any of the s
``` ```
/* xxx.css */ /* xxx.css */
.container { .container {
width: 100%;
height: 100%;
align-items: center; align-items: center;
flex-direction: column; flex-direction: column;
justify-content: center; justify-content: center;
...@@ -102,15 +108,15 @@ export default { ...@@ -102,15 +108,15 @@ export default {
![en-us_image_0000001223287672](figures/en-us_image_0000001223287672.gif) ![en-us_image_0000001223287672](figures/en-us_image_0000001223287672.gif)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> - For wearables, the input type can only be button, radio, or checkbox. > - For wearables, the input type can only be **button**, **radio**, or **checkbox**.
> >
> - The settings of checked take effect only when the input type is set to checkbox or radio. The default value of checked is false. > - The settings of **checked** take effect only when the input type is set to **checkbox** or **radio**. The default value of **checked** is **false**.
## Event Binding ## Event Binding
Add the search and translate events to the <input> component. Add the **search** and **translate** events to the **&lt;input&gt;** component.
``` ```
<!-- xxx.hml --> <!-- xxx.hml -->
...@@ -128,6 +134,7 @@ export default { ...@@ -128,6 +134,7 @@ export default {
/* xxx.css */ /* xxx.css */
.content { .content {
width: 100%; width: 100%;
height: 100%;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
...@@ -170,7 +177,7 @@ export default { ...@@ -170,7 +177,7 @@ export default {
## Setting the Input Error Message ## Setting the Input Error Message
Add the showError method to the <input> component to display an error message in the event of incorrect input. Add the **showError** method to the **&lt;input&gt;** component to display an error message in the event of incorrect input.
``` ```
...@@ -187,6 +194,7 @@ Add the showError method to the <input> component to display an error message in ...@@ -187,6 +194,7 @@ Add the showError method to the <input> component to display an error message in
/* xxx.css */ /* xxx.css */
.content { .content {
width: 100%; width: 100%;
height: 100%;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
...@@ -219,9 +227,13 @@ import prompt from '@system.prompt' ...@@ -219,9 +227,13 @@ import prompt from '@system.prompt'
}, },
buttonClick(e){ buttonClick(e){
if(this.value.length > 6){ if(this.value.length > 6){
this.$element("input").showError({ error: 'Up to 6 characters are allowed.' }); this.$element("input").showError({
error: 'Up to 6 characters are allowed.'
});
}else if(this.value.length == 0){ }else if(this.value.length == 0){
this.$element("input").showError({ error:this.value + 'This field cannot be left empty.' }); this.$element("input").showError({
error:this.value + 'This field cannot be left empty.'
});
}else{ }else{
prompt.showToast({ prompt.showToast({
message: "success " message: "success "
...@@ -233,14 +245,14 @@ import prompt from '@system.prompt' ...@@ -233,14 +245,14 @@ import prompt from '@system.prompt'
![en-us_image_0000001223127708](figures/en-us_image_0000001223127708.gif) ![en-us_image_0000001223127708](figures/en-us_image_0000001223127708.gif)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> - This method is available when the input type is set to text, email, date, time, number, or password. > - This method is available when the input type is set to **text**, **email**, **date**, **time**, **number**, or **password**.
## Example Scenario ## Example Scenario
Enter information by using the <input> component of the type that suits your needs. Enter information by using the **&lt;input&gt;** component of the type that suits your needs.
......
# &lt;list&gt; Development # &lt;list&gt; Development
The &lt;list&gt; component provides a list container that presents a series of list items arranged in a column with the same width. Lists can be used for presenting the same type of data in a multiple and coherent row style. For details, see [list](../reference/arkui-js/js-components-container-list.md). The **&lt;list&gt;** component provides a list container that presents a series of list items arranged in a column with the same width. Lists can be used for presenting the same type of data in a multiple and coherent row style. For details, see [list](../reference/arkui-js/js-components-container-list.md).
## Creating a &lt;list&gt; Component ## Creating a &lt;list&gt; Component
Create a &lt;list&gt; component in the .hml file under pages/index. Create a **&lt;list&gt;** component in the .hml file under **pages/index**.
``` ```
<!-- index.hml --> <!-- index.hml -->
<div class="container"> <div class="container">
<list> <list-item class="listItem"></list-item> <list><list-item class="listItem"></list-item>
<list-item class="listItem"></list-item> <list-item class="listItem"></list-item>
<list-item class="listItem"></list-item> <list-item class="listItem"></list-item>
<list-item class="listItem"></list-item> <list-item class="listItem"></list-item>
...@@ -24,6 +24,8 @@ Create a &lt;list&gt; component in the .hml file under pages/index. ...@@ -24,6 +24,8 @@ Create a &lt;list&gt; component in the .hml file under pages/index.
``` ```
/* xxx.css */ /* xxx.css */
.container { .container {
width: 100%;
height: 100%;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
background-color: #F1F3F5; background-color: #F1F3F5;
...@@ -37,21 +39,21 @@ Create a &lt;list&gt; component in the .hml file under pages/index. ...@@ -37,21 +39,21 @@ Create a &lt;list&gt; component in the .hml file under pages/index.
![en-us_image_0000001223287680](figures/en-us_image_0000001223287680.png) ![en-us_image_0000001223287680](figures/en-us_image_0000001223287680.png)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> - &lt;list-item-group&gt; is a child component of the &lt;list&gt; component and is used to group items in a list. It can have a &lt;list-item&gt; nested inside, but not &lt;list&gt;. > - **&lt;list-item-group&gt;** is a child component of the **&lt;list&gt;** component and is used to group items in a list. It can have a **&lt;list-item&gt;** nested inside, but not **&lt;list&gt;**.
> >
> - &lt;list-item&gt; is a child component of the &lt;list&gt; component and is used to display items in a list. > - **&lt;list-item&gt;** is a child component of the **&lt;list&gt;** component and is used to display items in a list.
## Adding a Scrollbar ## Adding a Scrollbar
To display a scrollbar on the right side of the screen, set scrollbar to on. The side scrollbar can be used to scroll a long list or the screen up or down. To display a scrollbar on the right side of the screen, set **scrollbar** to **on**. The side scrollbar can be used to scroll a long list or the screen up or down.
``` ```
<!-- index.hml --> <!-- index.hml -->
<div class="container"> <div class="container">
<list class="listCss" scrollbar="on" > <list class="listCss" scrollbar="on">
<list-item class="listItem"></list-item> <list-item class="listItem"></list-item>
<list-item class="listItem"></list-item> <list-item class="listItem"></list-item>
<list-item class="listItem"></list-item> <list-item class="listItem"></list-item>
...@@ -66,6 +68,8 @@ To display a scrollbar on the right side of the screen, set scrollbar to on. The ...@@ -66,6 +68,8 @@ To display a scrollbar on the right side of the screen, set scrollbar to on. The
``` ```
/* index.css */ /* index.css */
.container { .container {
width: 100%;
height: 100%;
flex-direction: column; flex-direction: column;
background-color: #F1F3F5; background-color: #F1F3F5;
} }
...@@ -86,7 +90,7 @@ To display a scrollbar on the right side of the screen, set scrollbar to on. The ...@@ -86,7 +90,7 @@ To display a scrollbar on the right side of the screen, set scrollbar to on. The
## Adding a Side Index Bar ## Adding a Side Index Bar
Set a custom indexer component to add an index bar at the right boundary of a list. By default, an alphabetical indexer is used. Set a custom **indexer** component to add an index bar at the right boundary of a list. By default, an alphabetical indexer is used.
``` ```
...@@ -114,15 +118,15 @@ Set a custom indexer component to add an index bar at the right boundary of a li ...@@ -114,15 +118,15 @@ Set a custom indexer component to add an index bar at the right boundary of a li
![en-us_image_0000001223127716](figures/en-us_image_0000001223127716.png) ![en-us_image_0000001223127716](figures/en-us_image_0000001223127716.png)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> - This indexer attribute is valid only when flex-direction is set to column and columns is set to 1. > - This **indexer** attribute is valid only when **flex-direction** is set to **column** and **columns** is set to **1**.
> >
> - You must include "\#" when using a customized indexer. > - You must include **"\#"** when using a customized indexer.
## Collapsing or Expanding a List ## Collapsing or Expanding a List
To allow a &lt;list&gt; component to collapse and expand, add groupcollapse and groupexpand events. To allow a **&lt;list&gt;** component to collapse and expand, add **groupcollapse** and **groupexpand** events.
``` ```
...@@ -200,14 +204,16 @@ export default { ...@@ -200,14 +204,16 @@ export default {
![en-us_image_0000001267887845](figures/en-us_image_0000001267887845.gif) ![en-us_image_0000001267887845](figures/en-us_image_0000001267887845.gif)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> - The groupcollapse and groupexpand events can be used only by the list-item-group component. > - The **groupcollapse** and **groupexpand** events can be used only by the **list-item-group** component.
## Example Scenario ## Example Scenario
Search for contacts by using an alphabetical indexer. Search for contacts by using an alphabetical indexer.
``` ```
<!-- index.hml --> <!-- index.hml -->
<div class="doc-page"> <div class="doc-page">
...@@ -219,7 +225,7 @@ Search for contacts by using an alphabetical indexer. ...@@ -219,7 +225,7 @@ Search for contacts by using an alphabetical indexer.
<div class="container"> <div class="container">
<div class="in-container"> <div class="in-container">
<text class="name">{{$item.name}}</text> <text class="name">{{$item.name}}</text>
<text class="number">18888888888</text> <text class="phone">18888888888</text>
</div> </div>
</div> </div>
</list-item> </list-item>
...@@ -232,6 +238,8 @@ Search for contacts by using an alphabetical indexer. ...@@ -232,6 +238,8 @@ Search for contacts by using an alphabetical indexer.
</div> </div>
``` ```
``` ```
/* index.css */ /* index.css */
.doc-page { .doc-page {
...@@ -251,7 +259,7 @@ Search for contacts by using an alphabetical indexer. ...@@ -251,7 +259,7 @@ Search for contacts by using an alphabetical indexer.
color: #000000; color: #000000;
font-size: 39px; font-size: 39px;
} }
.number { .phone {
color: black; color: black;
font-size: 25px; font-size: 25px;
} }
...@@ -265,6 +273,8 @@ Search for contacts by using an alphabetical indexer. ...@@ -265,6 +273,8 @@ Search for contacts by using an alphabetical indexer.
} }
``` ```
``` ```
// xxx.js // xxx.js
export default { export default {
......
# &lt;marquee&gt; Development
The **&lt;marquee&gt;** component displays single-line scrolling text. For details, see [marquee](../reference/arkui-js/js-components-basic-marquee.md).
## Creating a &lt;marquee&gt; Component
Create a **&lt;marquee&gt;** component in the .hml file under **pages/index**.
```
<!-- xxx.hml -->
<div class="container">
<marquee style="width: 100%;height: 80px; color: #ffffff; background-color: #0820ef;padding-left: 200px;">This is a marquee.</marquee>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
```
![en-us_image_0000001231683172](figures/en-us_image_0000001231683172.png)
## Setting Attributes and Styles
Set the **color** and **font-weight** attributes to define the color, font weight, and border style of marquee text.
```
<!-- xxx.hml -->
<div class="container">
<marquee class="customMarquee">It's a racing lamp.</marquee>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
.customMarquee {
width: 100%;
height: 80px;
padding: 10px;
margin: 20px;
border: 4px solid #6712f1;
border-radius: 20px;
font-size: 40px;
color: #ffffff;
font-weight: bolder;
font-family: serif;
background-color: #1567f3;
}
```
![en-us_image_0000001275803193](figures/en-us_image_0000001275803193.png)
Set the **scrollamount**, **loop**, and **direction** attributes to define the maximum scroll length, number of scrolling times, and text scrolling direction.
```
<!-- xxx.hml -->
<div class="tutorial-page">
<div class="mymarquee">
<marquee loop="{{loopval}}" scrollamount="{{scroll}}" direction="{{isleft}}" class="marqueetext" id="testmarquee" onclick="makestart">
It's a racing lamp
</marquee>
</div>
<div style="width: 600px;height: 150px;flex-direction: row;justify-content: space-around;">
<button onclick="setleft" value="left"></button>
<button onclick="setright" value="right"></button>
</div>
</div>
```
```
/* xxx.css */
.tutorial-page {
width: 750px;
height: 100%;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: #F1F3F5;
}
.marqueetext {
color: #ffffff;
font-family: serif;
font-size: 37px;
}
.mymarquee {
margin-top: 20px;
width:100%;
height: 100px;
margin-left: 50px;
margin-right: 50px;
border: 1px solid #6712f1;
background-color: #1567f3;
border-radius: 15px;
align-items: center;
}
button{
width: 200px;
height: 80px;
margin-top: 100px;
}
```
```
// xxx.js
export default {
private: {
loopval: -1,
scroll: 10,
isleft: "left",
},
onInit(){
},
setleft(e) {
this.isleft = "left"
},
setright(e) {
this.isleft = "right"
},
makestart(e) {
this.$element('testmarquee').start()
}
}
```
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> When the value of **loop** is less than or equal to 0, the marquee scrolls continuously. If **loop** is not set, the default value **-1** is used.
![en-us_image_0000001276162773](figures/en-us_image_0000001276162773.gif)
## Example Scenario
In this example, you can control the scrolling of marquee text.
Set **loop** to **1**. When scrolling ends, trigger a **finish** event to increase the number of scrolling times by 1 and change the font color to a random color. Then, call the **start** method to start scrolling again.
```
<!-- xxx.hml -->
<div class="tutorial-page">
<div class="mymarquee">
<marquee style="color: {{color1}}" loop="{{loopval}}" scrollamount="{{scroll}}" direction="{{isleft}}" class="marqueetext"
id="testmarquee" onfinish="setfinish">
It's a racing lamp
</marquee>
</div>
<div style="width: 600px;height: 150px;flex-direction: row;justify-content: space-around;">
<button onclick="makestart" value="start"></button>
<button onclick="makestop" value="stop"></button>
</div>
</div>
```
```
/* xxx.css */
.tutorial-page {
width: 750px;
height: 100%;
flex-direction: column;
align-items: center;
justify-content: center;
}
.marqueetext {
font-size: 37px;
}
.mymarquee {
margin-top: 20px;
width:100%;
height: 100px;
margin-left: 50px;
margin-right: 50px;
border: 1px solid #dc0f27;
border-radius: 15px;
align-items: center;
}
button{
width: 200px;
height: 80px;
margin-top: 100px;
}
```
```
// xxx.js
export default {
private: {
loopval: 1,
scroll: 8,
color1: 'red'
},
onInit(){
},
setfinish(e) {
this.loopval= this.loopval + 1,
this.r = Math.floor(Math.random()*255),
this.g = Math.floor(Math.random()*255),
this.b = Math.floor(Math.random()*255),
this.color1 = 'rgba('+ this.r +','+ this.g +','+ this.b +',0.8)',
this.$element('testmarquee').start(),
this.loopval= this.loopval - 1
},
makestart(e) {
this.$element('testmarquee').start()
},
makestop(e) {
this.$element('testmarquee').stop()
}
}
```
![en-us_image_0000001276003541](figures/en-us_image_0000001276003541.gif)
# &lt;menu&gt; Development
The &lt;menu&gt; component serves as a temporary pop-up window to display operations that users can perform. For details, see [menu](../reference/arkui-js/js-components-basic-menu.md).
## Creating a &lt;menu&gt; Component
Create a **&lt;menu&gt;** component in the .hml file under **pages/index** and add the **target**, **type**, and **title** attributes.
```
<!-- xxx.hml-->
<div class="container">
<text class="title-text" id="textId">show menu</text>
<menu target="textId" type="click" title="title">
<option value="Item 1">Item 1</option>
<option value="Item 2">Item 2</option>
<option value="Item 3">Item 3</option>
</menu>
</div>
```
```
/* xxx.css */
.container{
width: 100%;
height: 100%;
flex-direction: column;
background-color: #F1F3F5;
align-items: center;
justify-content: center;
width: 100%;
}
.title-text{
font-size: 35px;
}
```
![en-us_image_0000001232162284](figures/en-us_image_0000001232162284.gif)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> - The **&lt;menu&gt;** component supports only the [option](../reference/arkui-js/js-components-basic-option.md) child component.
>
> - The **&lt;menu&gt;** component does not support the **focusable** and **disabled** attributes.
## Setting Styles
Set the style for the **&lt;menu&gt;** component, such as the font color, size, and character spacing.
```
<!-- xxx.hml-->
<div class="container">
<text class="title-text" id="textId">show menu</text>
<menu target="textId" type="click" title="title">
<option value="Item 1">Item 1</option>
<option value="Item 2">Item 2</option>
<option value="Item 3">Item 3</option>
</menu>
</div>
```
```
/* xxx.css */
.container{
width: 100%;
height: 100%;
flex-direction: column;
background-color: #F1F3F5;
align-items: center;
justify-content: center;
width: 100%;
}
.title-text{
font-size: 35px;
background-color: #5a5aee;
color: white;
width: 70%;
text-align: center;
height: 85px;
border-radius: 12px;
}
menu{
text-color: blue;
font-size: 35px;
letter-spacing: 2px;
}
option{
color: #6a6aef;
font-size: 30px;
}
```
![en-us_image_0000001275803137](figures/en-us_image_0000001275803137.gif)
## Binding Events
Bind the **&lt;menu&gt;** component with the **onselected** event (triggered when a value in the menu is selected) and the **oncancel** event (triggered when an operation is canceled). Click the **&lt;text&gt;** component to call the **show** method to set the coordinates of the **&lt;menu&gt;** component.
```
<!-- xxx.hml-->
<div class="container">
<text class="title-text" id="textId" onclick="textClick">show menu</text>
<menu title="title" onselected="select" oncancel="cancel" id="menuId">
<option value="Item 1">Item 1</option>
<option value="Item 2">Item 2</option>
<option value="Item 3">Item 3</option>
</menu>
</div>
```
```
/* xxx.css */
.container{
width: 100%;
height: 100%;
flex-direction: column;
background-color: #F1F3F5;
width: 100%;
}
.title-text{
font-size: 35px;
background-color: #5a5aee;
color: white;
width: 70%;
text-align: center;
height: 85px;
border-radius: 12px;
margin-top: 500px;
margin-left: 15%;
}
menu{
text-color: blue;
font-size: 35px;
letter-spacing: 2px;
}
option{
color: #6a6aef;
font-size: 30px;
}
```
```
// index.js
import prompt from '@system.prompt';
export default {
select(e) {
prompt.showToast({
message: e.value
})
},
cancel(){
prompt.showToast({
message: "cancel"
})
},
textClick() {
this.$element("menuId").show({x:175,y:590});
},
}
```
![en-us_image_0000001276162713](figures/en-us_image_0000001276162713.gif)
## Example Scenario
Click the **&lt;toggle&gt;** component to change the text color and select the **&lt;menu&gt;** component to change the size of the gradient color block.
```
<!-- xxx.hml-->
<div class="container">
<div class="contentToggle">
<toggle class="toggle" for="{{item in togglesList}}" onclick="toggleClick({{$idx}})" checked="{{item.checked}}">{{item.name}}</toggle>
</div>
<text class="size" style="color: {{color}};">width:{{width}},height:{{height}}</text>
<div style="width: {{width}}'px';height: {{height}}px;background:linear-gradient(to right,#FF0000,#0000FF);"></div>
<text id="menuId" class="text">change size</text>
<menu onselected="select" oncancel="cancel" target="menuId">
<option value="{{item.value}}" for="item in optionList">{{item.text}}</option>
</menu>
</div>
```
```
/* xxx.css */
.container{
flex-direction: column;
background-color: #F1F3F5;
width: 100%;
justify-content: center;
align-items: center;
}
.contentToggle{
width: 100%;
justify-content: space-around;
}
.toggle{
padding: 10px;
height:80px;
font-size: 35px;
width: 200px;
height: 85px;
}
.size{
width: 100%;
height: 200px;
text-align: center;
font-size: 40px;
text-align: center;
}
.text{
width: 300px;
height: 80px;
background-color: #615def;
color: white;
font-size: 35px;
text-align: center;
margin-top: 100px;
}
menu{
text-color: blue;
font-size: 35px;
letter-spacing: 2px;
}
option{
color: #6a6aef;
font-size: 30px;
}
```
```
// index.js
import prompt from '@system.prompt';
export default {
data:{
fresh: false,
width: 200,
height: 200,
color: '',
optionList:[
{text:'200 x 200',value:2},
{text:'300 x 300',value:3},
{text:'500 x 500',value:5},
],
togglesList:[
{name:"red", checked:false},
{name:"blue", checked:false},
{name: "black", checked:false},
],
},
toggleClick(index){
for(let i=0;i<this.togglesList.length;i++){
if(i == index){
this.color = this.togglesList[index].name;
this.togglesList[i].checked = true;
}else{
this.togglesList[i].checked = false;
}
}
},
select(e) {
this.width = e.value * 100;
this.height = e.value * 100;
}
}
```
![en-us_image_0000001276003485](figures/en-us_image_0000001276003485.gif)
# OffscreenCanvas
Create an **OffscreenCanvas** canvas and create a **getContext2d** object on the canvas. Then, create an image and set the **filter** attribute to change the image style.
```
<!-- xxx.hml -->
<div class="container">
<canvas ref="canvas1"></canvas>
<select @change="change()">
<option value="blur(5px)">blur</option>
<option value="grayscale(50%)">grayscale</option>
<option value="hue-rotate(45deg)">hue-rotate</option>
<option value="invert(100%)">invert</option>
<option value="drop-shadow(8px 8px 10px green)">drop-shadow</option>
<option value="brightness(0.4)">brightness</option>
<option value="opacity(0.25)">opacity</option>
<option value="saturate(30%)">saturate</option>
<option value="sepia(60%)">sepia</option>
<option value="contrast(200%)">contrast</option>
</select>
</div>
```
```
/* xxx.css */
.container{
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
canvas{
width: 600px;
height: 500px;
background-color: #fdfdfd;
border: 5px solid red;
}
select{
margin-top: 50px;
width: 250px;
height: 100px;
background-color: white;
}
```
```
// xxx.js
import prompt from '@system.prompt';
export default {
data:{
el: null,
ctx: null,
offscreen: null,
offCanvas: null,
img: null,
},
onShow(){
this.ctx = this.$refs.canvas1.getContext("2d");
this.offscreen = new OffscreenCanvas(600, 500);
this.offCanvas = this.offscreen.getContext("2d");
this.img = new Image();
this.img.src = 'common/images/2.png';
// Invoked when the image is successfully obtained.
let _this = this;
this.img.onload = function() {
_this.offCanvas.drawImage(_this.img, 100, 100, 400, 300);
};
this.img.onerror = function() {
prompt.showToast({message:"error",duration:2000})
};
var bitmap = this.offscreen.transferToImageBitmap();
this.ctx.transferFromImageBitmap(bitmap);
},
change(e){
this.offCanvas.filter = e.newValue;
this.offCanvas.drawImage(this.img, 100, 100, 400, 300);
var bitmap = this.offscreen.transferToImageBitmap();
this.ctx.transferFromImageBitmap(bitmap);
},
}
```
![en-us_image_0000001232162292](figures/en-us_image_0000001232162292.gif)
## Determining the Position
Use **isPointInPath** and **isPointInStroke** to determine and show whether a coordinate is within the path area and whether a coordinate is on the edge of the path.
```
<!-- xxx.hml -->
<div class="container">
<div class="content">
<text>Coordinate: {{X}}, {{Y}}</text>
<text>In path:{{textValue}}</text>
<text>In stroke:{{textValue1}}</text>
</div>
<canvas ref="canvas"></canvas>
<button onclick="change">Add(50)</button>
</div>
```
```
/* xxx.css */
.container{
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
canvas{
width: 600px;
height: 500px;
background-color: #fdfdfd;
border: 5px solid red;
}
.content{
flex-direction: column;
justify-content: center;
align-items: center;
}
text{
font-size: 30px;
width: 300px;
height: 80px;
text-align: center;
}
button{
width: 180px;
height: 75px;
margin-top: 50px;
}
```
```
// xxx.js
export default {
data: {
textValue: 0,
textValue1: 0,
X:0,
Y:250,
},
onShow(){
let canvas = this.$refs.canvas.getContext('2d');
let offscreen = new OffscreenCanvas(500,500);
let offscreenCanvasCtx = offscreen.getContext("2d");
let offscreenCanvasCtx1 = offscreen.getContext("2d");
offscreenCanvasCtx1.arc(this.X, this.Y, 2, 0, 6.28);
offscreenCanvasCtx.lineWidth=20;
offscreenCanvasCtx.rect(200,150, 200, 200);
offscreenCanvasCtx.stroke();
this.textValue1 = offscreenCanvasCtx.isPointInStroke(this.X, this.Y)?'true':'false';
this.textValue = offscreenCanvasCtx.isPointInPath(this.X, this.Y)?'true':'false';
let bitmap = offscreen.transferToImageBitmap();
canvas.transferFromImageBitmap(bitmap);
},
change(){
if(this.X < 500){
this.X = this.X+50;
}else{
this.X = 0;
}
let canvas = this.$refs.canvas.getContext('2d');
let offscreen = new OffscreenCanvas(500,500);
let offscreenCanvasCtx = offscreen.getContext("2d");
let offscreenCanvasCtx1 = offscreen.getContext("2d");
offscreenCanvasCtx1.arc(this.X, this.Y, 1, 0, 6.28)
offscreenCanvasCtx.lineWidth=20
offscreenCanvasCtx.rect(200,150, 200, 200);
offscreenCanvasCtx.stroke();
this.textValue1 = offscreenCanvasCtx.isPointInStroke(this.X, this.Y)?'true':'false';
this.textValue = offscreenCanvasCtx.isPointInPath(this.X, this.Y)?'true':'false';
let bitmap = offscreen.transferToImageBitmap();
canvas.transferFromImageBitmap(bitmap);
}
}
```
![en-us_image_0000001276003489](figures/en-us_image_0000001276003489.gif)
# Path2D
**&lt;Path2D&gt;** allows you to describe a path through an existing path. This path can be drawn through the **stroke** API of **Canvas**. For details, see [Path2D](../reference/arkui-js/js-components-canvas-path2d.md).
## Drawing Line Segments
Create a **&lt;Path2D&gt;** object and use line segments to create different shapes.
```
<!-- xxx.hml -->
<div class="container">
<canvas ref="canvas"></canvas>
</div>
```
```
/* xxx.css */
.container{
flex-direction: column;
background-color: #F1F3F5;
align-items: center;
justify-content: center;
width: 100%;
}
canvas{
width: 600px;
height: 600px;
background-color: #fdfdfd;
border: 5px solid red;
}
```
```
// xxx.js
import prompt from '@system.prompt';
export default {
onShow(){
let ctx = this.$refs.canvas.getContext('2d',{antialias: true});
let path = ctx.createPath2D();
// Roof
path.moveTo(10, 300);
path.lineTo(210,100);
path.lineTo(410, 300);
// House
path.moveTo(10, 300);
path.lineTo(410, 300);
path.lineTo(410, 600);
path.lineTo(10, 600);
path.closePath();
// Window
path.moveTo(50, 450);
path.bezierCurveTo(70, 350, 130, 350, 150, 450);
path.closePath();
// Door
path.moveTo(250, 450);
path.rect(250, 450, 350, 600);
path.closePath();
// Chimney
path.moveTo(365, 250);
path.ellipse(310, 215, 30, 130,0, Math.PI * 0.04, Math.PI * 1.1, 1);
// Tree
path.moveTo(485, 450);
path.quadraticCurveTo(510, 500, 485, 600);
path.moveTo(550, 450);
path.quadraticCurveTo(525, 500, 550, 600);
path.moveTo(600, 535);
path.arc(520, 450, 85, 0, 6);
ctx.stroke(path);
},
}
```
![en-us_image_0000001232002968](figures/en-us_image_0000001232002968.png)
## Drawing Graphs
Use **createPath2D** to create a path object and draw only **path1** so that only **path1** is displayed on the canvas. Click the **&lt;text&gt;** component to trigger the **addPath** method. The **path2** object is passed to **path1** as a parameter. After the **stroke** operation is performed on the **path1** object, **path1** and **path2** are displayed on the canvas. Click **Change** to change the value of **setTransform** to** setTransform(2, 0.1, 0.1, 2, 0,0)**. The graph is enlarged and tilted to the left.
```
<!-- xxx.hml -->
<div class="container">
<canvas ref="canvas"></canvas>
<div class="content">
<text onclick="addPath">{{ isAdd }}</text>
<text onclick="setTransform">{{textName}}</text>
</div>
</div>
```
```
/* xxx.css */
.container{
flex-direction: column;
background-color: #F1F3F5;
align-items: center;
justify-content: center;
width: 100%;
}
canvas{
width: 600px;
height: 600px;
background-color: #fdfdfd;
border: 5px solid red;
}
.content{
width: 80%;
margin-top: 50px;
margin-bottom: 50px;
display: flex;
flex-wrap: wrap;
justify-content: space-around;
}
text{
width: 150px;
height: 80px;
color: white;
border-radius: 20px;
text-align: center;
background-color: #6060e7;
margin-bottom: 30px;
}
```
```
// xxx.js
import prompt from '@system.prompt';
export default {
data:{
ctx: null,
path1: null,
path2: null,
path3: null,
isAdd: "addPath2",
isChange: true,
textName: 'change'
},
onShow(){
this.ctx = this.$refs.canvas.getContext('2d',{antialias:true});
this.path1 = this.ctx.createPath2D();
this.path1.moveTo(200, 200);
this.path1.lineTo(400, 200);
this.path1.lineTo(400, 400);
this.path1.lineTo(200, 400);
this.path1.closePath();
this.path2 = this.ctx.createPath2D();
this.path2.arc(300, 300, 75, 0, 6.28)
this.ctx.stroke(this.path1);
},
addPath(){
if(this.isAdd == "addPath2"){
this.ctx.clearRect(0,0,600,600)
this.ctx.beginPath();
this.path2.addPath(this.path1)
this.ctx.stroke(this.path2);
this.isAdd = "clearPath2"
}else{
this.ctx.clearRect(0,0,600,600)
this.ctx.stroke(this.path1);
this.isAdd = "addPath2"
}
},
setTransform(){
if(this.isChange){
this.ctx.clearRect(0,0,600,600)
this.path3 = this.ctx.createPath2D();
this.path3.arc(150, 150, 100, 0, 6.28)
this.path3.setTransform(2, 0.1, 0.1, 2, 0,0);
this.ctx.stroke(this.path3);
this.isChange = !this.isChange;
this.textName = "back"
}else{
this.ctx.clearRect(0,0,600,600)
this.path3.setTransform(0.5, -0.1, -0.1, 0.5, 0,0);
this.ctx.stroke(this.path3);
this.isChange = !this.isChange;
this.textName = "change"
}
},
}
```
![en-us_image_0000001231683112](figures/en-us_image_0000001231683112.gif)
# &lt;picker&gt; Development # &lt;picker&gt; Development
The &lt;picker&gt; component supports common, date, time, data and time, and multi-column text selectors. For details, see [picker](../reference/arkui-js/js-components-basic-picker.md). The **&lt;picker&gt;** component supports common, date, time, data and time, and multi-column text selectors. For details, see [picker](../reference/arkui-js/js-components-basic-picker.md).
## Creating a &lt;picker&gt; Component ## Creating a &lt;picker&gt; Component
Create a &lt;picker&gt; component in the .hml file under pages/index. Create a **&lt;picker&gt;** component in the .hml file under **pages/index**.
``` ```
<!-- index.hml --> <!-- index.hml -->
<div class="container"> <div class="container">
<picker> picker </picker> <picker>
picker
</picker>
<div> <div>
``` ```
...@@ -20,6 +22,8 @@ Create a &lt;picker&gt; component in the .hml file under pages/index. ...@@ -20,6 +22,8 @@ Create a &lt;picker&gt; component in the .hml file under pages/index.
``` ```
/* index.css */ /* index.css */
.container { .container {
width: 100%;
height: 100%;
flex-direction: column; flex-direction: column;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
...@@ -32,7 +36,7 @@ Create a &lt;picker&gt; component in the .hml file under pages/index. ...@@ -32,7 +36,7 @@ Create a &lt;picker&gt; component in the .hml file under pages/index.
## Setting the Picker Type ## Setting the Picker Type
Set the type attribute of the &lt;picker&gt; component. For example, set it to date. Set the **type** attribute of the **&lt;picker&gt;** component. For example, set it to **date**.
``` ```
...@@ -47,6 +51,8 @@ Set the type attribute of the &lt;picker&gt; component. For example, set it to d ...@@ -47,6 +51,8 @@ Set the type attribute of the &lt;picker&gt; component. For example, set it to d
``` ```
/* index.css */ /* index.css */
.container { .container {
width: 100%;
height: 100%;
flex-direction: column; flex-direction: column;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
...@@ -71,14 +77,15 @@ export default { ...@@ -71,14 +77,15 @@ export default {
![en-us_image_0000001267647893](figures/en-us_image_0000001267647893.gif) ![en-us_image_0000001267647893](figures/en-us_image_0000001267647893.gif)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> > - When setting the value range of a common selector, you must use the data binding mode.
> When setting the value range of a common selector, you must use the data binding mode. >
> - The **lunarswitch** attribute of the date selector is only supported on phones and tablets.
## Setting the Time Format ## Setting the Time Format
Set the hours attribute to specify the time format used by the time selector. Available values include 12 and 24, indicating the 12-hour format and 24-hour format, respectively. Set the **hours** attribute to specify the time format used by the time selector. Available values include **12** and **24**, indicating the 12-hour format and 24-hour format, respectively.
``` ```
...@@ -93,6 +100,8 @@ Set the hours attribute to specify the time format used by the time selector. Av ...@@ -93,6 +100,8 @@ Set the hours attribute to specify the time format used by the time selector. Av
``` ```
/* index.css */ /* index.css */
.container { .container {
width: 100%;
height: 100%;
flex-direction: column; flex-direction: column;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
...@@ -107,15 +116,15 @@ Set the hours attribute to specify the time format used by the time selector. Av ...@@ -107,15 +116,15 @@ Set the hours attribute to specify the time format used by the time selector. Av
![en-us_image_0000001222807808](figures/en-us_image_0000001222807808.gif) ![en-us_image_0000001222807808](figures/en-us_image_0000001222807808.gif)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> - When hours is set to 12, the time is displayed in 12-hour format and distinguished by a.m. and p.m. > - When **hours** is set to **12**, the time is displayed in 12-hour format and distinguished by a.m. and p.m.
> >
> - When hours is set to 24, the time is displayed in 24-hour format. > - When **hours** is set to **24**, the time is displayed in 24-hour format.
## Adding Response Events ## Adding Response Events
To confirm and cancel selection, add change and cancel events. To confirm and cancel selection, add **change** and **cancel** events.
``` ```
...@@ -130,6 +139,8 @@ To confirm and cancel selection, add change and cancel events. ...@@ -130,6 +139,8 @@ To confirm and cancel selection, add change and cancel events.
``` ```
/* index.css */ /* index.css */
.container { .container {
width: 100%;
height: 100%;
flex-direction: column; flex-direction: column;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
...@@ -170,7 +181,9 @@ export default { ...@@ -170,7 +181,9 @@ export default {
## Example Scenario ## Example Scenario
Implement a health check-in application by using the &lt;picker&gt; component. Implement a health check-in application by using the **&lt;picker&gt;** component.
``` ```
<!-- index.hml --> <!-- index.hml -->
...@@ -202,6 +215,8 @@ Implement a health check-in application by using the &lt;picker&gt; component. ...@@ -202,6 +215,8 @@ Implement a health check-in application by using the &lt;picker&gt; component.
</div> </div>
``` ```
``` ```
/* index.css */ /* index.css */
.doc-page { .doc-page {
...@@ -244,6 +259,8 @@ Implement a health check-in application by using the &lt;picker&gt; component. ...@@ -244,6 +259,8 @@ Implement a health check-in application by using the &lt;picker&gt; component.
} }
``` ```
``` ```
// xxx.js // xxx.js
import pmt from '@system.prompt' import pmt from '@system.prompt'
......
# &lt;qrcode&gt; Development
The **&lt;qrcode&gt;** component is used to generate and display a QR code. For details, see [qrcode](../reference/arkui-js/js-components-basic-qrcode.md).
## Creating a &lt;qrcode&gt; Component
Create a **&lt;qrcode&gt;** component in the .hml file under **pages/index**.
```
<!-- xxx.hml-->
<div class="container">
<qrcode value="Hello"></qrcode>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: #F1F3F5;
}
```
![en-us_image_0000001275803133](figures/en-us_image_0000001275803133.png)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> The **value** parameter must be set.
## Setting the Component Type
Set the **type** attribute to select the QR code type from rectangle and circle.
```
<!-- xxx.hml-->
<div class="container">
<select onchange="settype">
<option for="{{bcol_list}}" value="{{$item}}">{{$item}}</option>
</select>
<qrcode value="Hello" type="{{qr_type}}"></qrcode>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: #F1F3F5;
}
select{
margin-top: 50px;
margin-bottom: 50px;
}
```
```
// index.js
export default {
data: {
qr_type: 'rect',
bcol_list: ['rect','circle']
},
settype(e) {
this.qr_type = e.newValue
},
}
```
![en-us_image_0000001275922965](figures/en-us_image_0000001275922965.gif)
## Setting Styles
Set the **color** and **background-color** attributes to set the color and background color of a QR code.
```
<!-- xxx.hml-->
<div class="container">
<qrcode value="Hello" type="rect"></qrcode>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: #F1F3F5;
}
qrcode{
width: 300px;
height: 300px;
color: blue;
background-color: #ffffff;
}
```
![en-us_image_0000001231683116](figures/en-us_image_0000001231683116.png)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> - If the values of **width** and **height** are different, the smaller value is used as the length of the QR code. The generated QR code is center displayed.
>
> - If either **width** or **height** is set, the value is used as the length of the QR code. If neither of them is set, the default length of 200 px is used.
>
## Example Scenario
In this example, you can bind a QR code to a text box, and change the QR code by replacing the content in the text box.
```
<!-- xxx.hml-->
<div class="container">
<input style="margin-bottom: 100px;" onchange="change"></input>
<qrcode value="{{textVal}}"></qrcode>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: #F1F3F5;
}
qrcode{
width: 400px;
height: 400px;
}
```
```
// index.js
export default{
data: {
textVal: ''
},
change(e){
this.textVal = e.value
}
}
```
![en-us_image_0000001232002972](figures/en-us_image_0000001232002972.gif)
# &lt;rating&gt; Development
The **&lt;rating&gt;** component provides a rating bar used for reviews and ratings. For details, see [rating](../reference/arkui-js/js-components-basic-rating.md).
## Creating a &lt;rating&gt; Component
Create a **&lt;rating&gt;** component in the .hml file under **pages/index**.
```
<!-- xxx.hml -->
<div class="container">
<rating></rating>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
rating {
width: 80%;
height: 150px;
}
```
![en-us_image_0000001231843116](figures/en-us_image_0000001231843116.gif)
## Setting the Rating Level
Use the **&lt;rating&gt;** component to set the number of stars in a rating bar and the current rating using the **numstars** and **rating** attributes, respectively.
```
<!-- xxx.hml -->
<div class="container">
<ratingnumstars="6" rating="5">
</rating>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
rating {
width: 80%;
height: 150px;
}
```
![en-us_image_0000001232003012](figures/en-us_image_0000001232003012.gif)
## Setting the Rating Style
Use the **&lt;rating&gt;** component to set the background images when a rating star is unselected, selected, and partially selected using the **star-background**, **star-foreground**, and **star-secondary** attributes, respectively.
```
<!-- xxx.hml -->
<div class="container">
<div style="width: 500px;height: 500px;align-items: center;justify-content: center;flex-direction: column;;">
<rating numstars="5" rating="1" class="myrating" style="width: {{ratewidth}}; height:{{rateheight}};
star-background: {{backstar}}; star-secondary: {{secstar}};star-foreground: {{forestar}};rtl-flip: true;">
</rating>
</div>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: #F1F3F5;
}
```
```
/* index.js */
export default {
data: {
backstar: 'common/love.png',
secstar: 'common/love.png',
forestar: 'common/love1.png',
ratewidth: '400px',
rateheight: '150px'
},
onInit(){
}
}
```
![en-us_image_0000001275803173](figures/en-us_image_0000001275803173.gif)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> - You must set **star-background**, **star-secondary**, and **star-foreground**. Otherwise, the grey rating star applies, indicating that the image source is incorrectly set.
>
> - The **star-background**, **star-secondary**, and **star-foreground** attributes support only PNG and JPG images in the local path.
## Binding Events
Add the **change** event to the &lt;rating&gt; component to print the current rating.
```
<!-- xxx.hml -->
<div class="container">
<rating numstars="5" rating="0" onchange="showrating"></rating>
</div>
```
```
.container {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
rating {
width: 80%;
height: 150px;
}
```
```
import prompt from '@system.prompt';
export default {
showrating(e) {
prompt.showToast({
message:'Current Rating' + e.rating
})
}
}
```
![en-us_image_0000001276003525](figures/en-us_image_0000001276003525.gif)
## Example Scenario
Change the switch status to toggle between the star background images and drag the slider to adjust the rating values.
```
<!-- xxx.hml -->
<div style="width: 100%;height:100%;flex-direction: column;align-items: center;background-color: #F1F3F5;">
<div style="width: 500px;height: 500px;align-items: center;justify-content: center;flex-direction: column;;">
<rating numstars="{{stars}}" rating="{{rate}}" stepsize="{{step}}" onchange="showrating" class="myrating"
style="width: {{ratewidth}};height:{{rateheight}};star-background: {{backstar}};star-secondary: {{secstar}};
star-foreground: {{forestar}};rtl-flip: true;"></rating>
</div>
<div style="flex-direction: column;width: 80%;align-items: center;">
<div style="width: 100%;height: 100px;align-items: center;justify-content: space-around;">
<text>Replacing a custom image</text>
<switch checked="false" showtext="true" onchange="setstar"></switch>
</div>
<div style="width: 100%;height:120px;margin-top: 50px;margin-bottom: 50px;flex-direction: column;align-items: center;
justify-content: space-around;">
<text>numstars {{stars}}</text>
<slider id="sli1" min="-1" max="10" value="5" step="1" onchange="setnumstars"></slider>
</div>
<div style="width: 100%;height:120px;flex-direction: column;align-items: center;justify-content: space-around;">
<text>rating {{rate}}</text>
<slider id="sli2" min="-1" max="10" value="0" step="1" onchange="setrating"></slider>
</div>
</div>
</div>
```
```
/* xxx.css */
.myrating:active {
width: 500px;
height: 100px;
}
switch{
font-size: 40px;
}
```
```
/* index.js */
import prompt from '@system.prompt';
export default {
data: {
backstar: '',
secstar: '',
forestar: '',
stars: 5,
ratewidth: '300px',
rateheight: '60px',
step: 0.5,
rate: 0
},
onInit(){
},
setstar(e) {
if (e.checked == true) {
this.backstar = 'common/love.png'
this.secstar = 'common/love.png'
this.forestar = 'common/love1.png'
} else {
this.backstar = ''
this.secstar = ''
this.forestar = ''
}
},
setnumstars(e) {
this.stars = e.progress
this.ratewidth = 60 * parseInt(this.stars) + 'px'
},
setstep(e) {
this.step = e.progress
},
setrating(e){
this.rate = e.progress
},
showrating(e) {
prompt.showToast({
message:'Current Rating' + e.rating
})
}
}
```
![en-us_image_0000001275923005](figures/en-us_image_0000001275923005.gif)
# &lt;search&gt; Development
The **&lt;search&gt;** component provides an input area for users to search. For details, see [search](../reference/arkui-js/js-components-basic-search.md).
## Creating a &lt;search&gt; Component
Create a **&lt;search&gt;** component in the .hml file under **pages/index**.
```
<!-- xxx.hml-->
<div class="container">
<search></search>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: #F1F3F5;
}
```
![en-us_image_0000001276003537](figures/en-us_image_0000001276003537.png)
## Setting Attributes
Set the **hint**, **icon**, and **searchbutton** to define the hint text, icon, and search button at the end of the search box.
```
<!-- xxx.hml-->
<div class="container">
<search hint="Please enter the search content" searchbutton="search" icon="/common/search1.png"></search>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: #F1F3F5;
}
```
![en-us_image_0000001275923017](figures/en-us_image_0000001275923017.png)
## Adding Styles
Set **color**, **placeholder**, and **caret-color** to set the text color, hint text color, and cursor color of the search box.
```
<!-- xxx.hml-->
<div class="container">
<search hint="Please enter the search content" searchbutton="search" ></search>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: #F1F3F5;
}
search{
color: black;
placeholder-color: black;
caret-color: red;
}
```
![en-us_image_0000001232003020](figures/en-us_image_0000001232003020.gif)
## Binding Events
Add the **change**, **search**, **submit**, **share**, and **translate** events to the **&lt;search&gt;** component to perform operations on the input information.
```
<!-- xxx.hml-->
<div class="container">
<text style="margin-left: -7px;">
<span>Enter text and then touch and hold what you've entered</span>
</text>
<search hint="Please enter the search content" searchbutton="search" onsearch="search" onchange="change" ontranslate="translate" onshare="share"
onsubmit="submit">
</search>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: #F1F3F5;
}
text{
width: 100%;
font-size: 25px;
text-align: center;
margin-bottom: 100px;
}
```
```
// index.js
import prompt from '@system.prompt'
export default {
search(e){
prompt.showToast({
message: e.value,
duration: 3000,
});
},
translate(e){
prompt.showToast({
message: e.value,
duration: 3000,
});
},
share(e){
prompt.showToast({
message: e.value,
duration: 3000,
});
},
change(e){
prompt.showToast({
message: e.value,
duration: 3000,
});
},
submit(e){
prompt.showToast({
message: 'submit',
duration: 3000,
});
}
}
```
![en-us_image_0000001231683164](figures/en-us_image_0000001231683164.gif)
## Example Scenario
In this example, you can select the **&lt;search&gt;**, **&lt;textarea&gt;**, or **&lt;input&gt;** component from the drop-down list box to implement the respective function.
```
<!-- xxx.hml-->
<div style="flex-direction: column;align-items: center;justify-content: center; width: 100%;">
<select class="slt1" id="slt1" onchange="setfield">
<option value="search">Search</option>
<option value="textarea">Textarea</option>
<option value="input">Input</option>
</select>
<div if="{{showsearch}}" style="flex-direction: column;align-items: center;margin-top: 50px;height: 400px;justify-content: space-around;">
<search class="field" id="search1" hint="search1" onsubmit="submit" onchange="change" ></search>
<search class="field" id="search2" icon="common/search1.png" hint="search2" show="{{showsec}}" onsubmit="submit" onchange="change" ></search>
</div>
<div if="{{showtextarea}}" style="flex-direction: column;align-items: center;margin-top: 50px;height: 400px;justify-content: space-around;">
<textarea class="field" id="textarea1" extend="true" placeholder="textarea1" onchange="change" ></textarea>
<textarea class="field" id="textarea2" extend="true" placeholder="textarea2" onchange="change" show="{{showsec}}"></textarea>
</div>
<div if="{{showinput}}" style="flex-direction: column;align-items: center;margin-top: 50px;height: 400px;justify-content: space-around;">
<input type="text" class="field" id="input1" placeholder="input1" onchange="change" ></input>
<input type="text" class="field" id="input2" placeholder="input2" onchange="change" show="{{showsec}}"></input>
</div>
</div>
```
```
/* xxx.css */
.field {
width: 80%;
color: mediumaquamarine;
font-weight: 600;
placeholder-color: orangered;
}
.slt1{
font-size: 50px;
position: absolute;
left: 50px;
top: 50px;
}
```
```
// index.js
import prompt from '@system.prompt';
export default {
data: {
showsearch: true,
showtextarea: false,
showinput: false,
showsec: true,
},
setfield(e) {
this.field = e.newValue
if (e.newValue == 'search') {
this.showsearch = true
this.showtextarea = false
this.showinput = false
} else if (e.newValue == 'textarea') {
this.showsearch = false
this.showtextarea = true
this.showinput = false
} else {
this.showsearch = false
this.showtextarea = false
this.showinput = true
}
},
submit(e) {
prompt.showToast({
message: 'Search!',
duration: 2000
})
},
change(e) {
prompt.showToast({
message: 'Content:'+ e.text,
duration: 2000
})
}
}
```
![en-us_image_0000001232003024](figures/en-us_image_0000001232003024.gif)
# &lt;slider&gt; Development
The **&lt;slider&gt;** component is used to quickly adjust settings, such as the volume and brightness. For details, see [slider](../reference/arkui-js/js-components-basic-slider.md).
## Creating a &lt;slider&gt; Component
Create a **&lt;slider&gt;** component in the .hml file under **pages/index**.
```
<!-- xxx.hml -->
<div class="container">
<slider></slider>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
background-color: #F1F3F5;
flex-direction: column;
justify-content: center;
align-items: center;
}
```
![en-us_image_0000001232162312](figures/en-us_image_0000001232162312.gif)
## Setting Styles and Attributes
Use the **&lt;slider&gt;** component to set the background color, selected color, and slider color using the **color**, **selected-color**, and **block-color** attributes, respectively.
```
<!-- xxx.hml -->
<div class="container">
<slider class= "sli"></slider>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
.sli{
color: #fcfcfc;
scrollbar-color: aqua;
background-color: #b7e3f3;
}
```
![en-us_image_0000001232003000](figures/en-us_image_0000001232003000.gif)
Add the **mix**, **max**, **value**, **step**, and **mode** attributes to set the minimum value, maximum value, initial value, step, and style of the slider.
```
<!-- xxx.hml -->
<div class="container">
<slider min="0" max="100" value="1" step="2" mode="inset" showtips="true"></slider>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
```
![en-us_image_0000001276003517](figures/en-us_image_0000001276003517.gif)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> Set the **mode** attribute to specify the slider style, which takes effect only on mobile phones and tablets. It can be set to:
>
> - **outset**: The slider is on the sliding bar.
>
> - **inset**: The slider is inside the sliding bar.
## Binding Events
Add the **change** event to the **&lt;rating&gt;** component and pass the ChangeEvent attribute when adding the event.
```
<!-- xxx.hml -->
<div class="container">
<text>slider start value is {{startValue}}</text>
<text>slider current value is {{currentValue}}</text>
<text>slider end value is {{endValue}}</text>
<slider min="0" max="100" value="{{value}}" onchange="setvalue"></slider>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
```
```
// xxx.js
export default {
data: {
value: 0,
startValue: 0,
currentValue: 0,
endValue: 0,
},
setvalue(e) {
if (e.mode == "start") {
this.value = e.value;
this.startValue = e.value;
} else if (e.mode == "move") {
this.value = e.value;
this.currentValue = e.value;
} else if (e.mode == "end") {
this.value = e.value;
this.endValue = e.value;
}
}
}
```
![en-us_image_0000001275803169](figures/en-us_image_0000001275803169.gif)
## Example Scenario
Adjust the value of the slider to change the image size and dynamically print the width and height of the current image.
```
<!-- xxx.hml -->
<div class="container">
<image src="common/landscape3.jpg" style=" width: {{WidthVal}}px;height:{{HeightVal}}px;margin-top: -150px;"></image>
<div class="txt">
<slider min="0" max="100" value="{{value}}" onchange="setvalue"></slider>
<text>The width of this picture is {{WidthVal}}</text>
<text>The height of this picture is {{HeightVal}}</text>
</div>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
.txt{
flex-direction: column;
justify-content: center;
align-items: center;
position: fixed;
top: 65%;
}
text{
margin-top: 30px;
}
```
```
// xxx.js
export default{
data: {
value: 0,
WidthVal: 200,
HeightVal: 200
},
setvalue(e) {
this.WidthVal = 200 + e.value;
this.HeightVal = 200 + e.value
}
}
```
![en-us_image_0000001275922997](figures/en-us_image_0000001275922997.gif)
# &lt;stepper&gt; Development # &lt;stepper&gt; Development
When multiple steps are required to complete a task, you can use the &lt;stepper&gt; component to navigate your users through the whole process. For details, see [stepper](../reference/arkui-js/js-components-container-stepper.md). When multiple steps are required to complete a task, you can use the **&lt;stepper&gt;** component to navigate your users through the whole process. For details, see [stepper](../reference/arkui-js/js-components-container-stepper.md).
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> This component is supported since API version 5. > This component is supported since API version 5.
## Creating a &lt;stepper&gt; Component ## Creating a &lt;stepper&gt; Component
Create a &lt;stepper&gt; component in the .hml file under pages/index. Create a **&lt;stepper&gt;** component in the .hml file under **pages/index**.
``` ```
<!-- index.hml --> <!-- index.hml -->
<div class="container"> <div class="container">
<stepper> <stepper-item> <stepper><stepper-item>
<text>Step 1</text> <text>Step 1</text>
</stepper-item> </stepper-item>
<stepper-item> <stepper-item>
<text>Step 2</text> <text>Step 2</text>
</stepper-item> </stepper-item>
</stepper> </stepper>
</div> </div>
``` ```
...@@ -30,6 +30,8 @@ Create a &lt;stepper&gt; component in the .hml file under pages/index. ...@@ -30,6 +30,8 @@ Create a &lt;stepper&gt; component in the .hml file under pages/index.
``` ```
/* xxx.css */ /* xxx.css */
.container { .container {
width: 100%;
height: 100%;
flex-direction: column; flex-direction: column;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
...@@ -47,7 +49,7 @@ text{ ...@@ -47,7 +49,7 @@ text{
## Setting the Index ## Setting the Index
Set index to the index value of the step that you want to display by default. Set **index** to the index value of the step that you want to display by default.
``` ```
...@@ -71,6 +73,8 @@ Set index to the index value of the step that you want to display by default. ...@@ -71,6 +73,8 @@ Set index to the index value of the step that you want to display by default.
``` ```
/* index.css */ /* index.css */
.container { .container {
width: 100%;
height: 100%;
flex-direction: column; flex-direction: column;
background-color:#F1F3F5; background-color:#F1F3F5;
} }
...@@ -83,7 +87,7 @@ text{ ...@@ -83,7 +87,7 @@ text{
![en-us_image_0000001267767837](figures/en-us_image_0000001267767837.gif) ![en-us_image_0000001267767837](figures/en-us_image_0000001267767837.gif)
Set the label attribute to customize the button text for the &lt;stepper-item&gt;. Set the **label** attribute to customize the button text for the **&lt;stepper-item&gt;**.
``` ```
...@@ -110,6 +114,8 @@ Set the label attribute to customize the button text for the &lt;stepper-item&gt ...@@ -110,6 +114,8 @@ Set the label attribute to customize the button text for the &lt;stepper-item&gt
``` ```
/* index.css */ /* index.css */
.container { .container {
width: 100%;
height: 100%;
flex-direction: column; flex-direction: column;
background-color:#F1F3F5; background-color:#F1F3F5;
} }
...@@ -125,7 +131,10 @@ text{ ...@@ -125,7 +131,10 @@ text{
/* index.js */ /* index.js */
export default { export default {
data: { data: {
label_1:{ nextLabel: 'NEXT', status: 'normal' }, label_1:{
nextLabel: 'NEXT',
status: 'normal'
},
label_2:{ label_2:{
prevLabel: 'BACK', prevLabel: 'BACK',
nextLabel: 'NEXT', nextLabel: 'NEXT',
...@@ -143,9 +152,9 @@ export default { ...@@ -143,9 +152,9 @@ export default {
![en-us_image_0000001267767841](figures/en-us_image_0000001267767841.gif) ![en-us_image_0000001267767841](figures/en-us_image_0000001267767841.gif)
## Setting the Style ## Setting Styles
By default, the &lt;stepper&gt; component fills entire space of its container. The sample code below shows how to set the border and background color using the border and background-color attributes. By default, the **&lt;stepper&gt;** component fills entire space of its container. The sample code below shows how to set the border and background color using the **border** and **background-color** attributes.
``` ```
<!-- index.hml --> <!-- index.hml -->
...@@ -164,6 +173,8 @@ export default { ...@@ -164,6 +173,8 @@ export default {
``` ```
/* index.css */ /* index.css */
.container { .container {
width: 100%;
height: 100%;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
...@@ -174,7 +185,8 @@ export default { ...@@ -174,7 +185,8 @@ export default {
height: 300px; height: 300px;
} }
.stepperClass{ .stepperClass{
border:1px solid silver ; background-color: white; border:1px solid silver;
background-color: white;
} }
text{ text{
width: 100%; width: 100%;
...@@ -188,12 +200,13 @@ text{ ...@@ -188,12 +200,13 @@ text{
## Adding Events ## Adding Events
The &lt;stepper&gt; component supports the finish, change, next, back, and skip events. The **&lt;stepper&gt;** component supports the **finish**, **change**, **next**, **back**, and **skip** events.
- When the change and next or back events exist at the same time, the next or back event is executed before the change event. - When the **change** and **next** or **back** events exist at the same time, the **next** or **back** event is executed before the **change** event.
- Before resetting the index attribute, you must remove the current value. Otherwise, the value change cannot be detected. - Before resetting the **index** attribute, you must remove the current value. Otherwise, the value change cannot be detected.
``` ```
<!-- index.hml --> <!-- index.hml -->
<div class="container" style="background-color:#F1F3F5;"> <div class="container" style="background-color:#F1F3F5;">
...@@ -219,6 +232,8 @@ The &lt;stepper&gt; component supports the finish, change, next, back, and skip ...@@ -219,6 +232,8 @@ The &lt;stepper&gt; component supports the finish, change, next, back, and skip
``` ```
/* xxx.css */ /* xxx.css */
.doc-page { .doc-page {
width: 100%;
height: 100%;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
...@@ -339,6 +354,8 @@ Use the &lt;stepper&gt; component to navigate through the steps. Create a [&lt;t ...@@ -339,6 +354,8 @@ Use the &lt;stepper&gt; component to navigate through the steps. Create a [&lt;t
``` ```
/* xxx.css */ /* xxx.css */
.container { .container {
width: 100%;
height: 100%;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
......
# Graph Drawing
The **&lt;svg&gt;** component can be used to draw simple shapes, such as rectangles, circles, and lines. For details about the supported shapes, see &lt;svg&gt;.
In this example, you can draw different shapes and stitch them to form a house graph.
```
<!-- xxx.hml -->
<div class="container">
<svg width="1000" height="1000">
<polygon points="100,400 300,200 500,400" fill="red"></polygon> // Rooftop
<polygon points="375,275 375,225 425,225 425,325" fill="orange"></polygon> // Chimney
<rect width="300" height="300" x="150" y="400" fill="orange"> // Main body
</rect>
<rect width="100" height="100" x="180" y="450" fill="white"> // Window
</rect>
<line x1="180" x2="280" y1="500" y2="500" stroke-width="4" fill="white" stroke="black"></line> // Window frame
<line x1="230" x2="230" y1="450" y2="550" stroke-width="4" fill="white" stroke="black"></line> // Window frame
<polygon points="325,700 325,550 400,550 400,700" fill="red"></polygon> // Door
<circle cx="380" cy="625" r="20" fill="black"></circle> // Doorknob
</svg>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
```
![en-us_image_0000001232162288](figures/en-us_image_0000001232162288.png)
# Basics
The **&lt;svg&gt;** component is used as the root node of the SVG canvas and can be nested in the SVG. For details, see [svg](../reference/arkui-js/js-components-svg.md).
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> - The APIs of this component are supported since API version 7.
>
> - The width and height must be defined for the **&lt;svg&gt;** parent component or **&lt;svg&gt;** component. Otherwise, the component is not drawn.
## Creating an &lt;svg&gt; Component
Create a **&lt;svg&gt;** component in the .hml file under **pages/index**.
```
<!-- xxx.hml -->
<div class="container">
<svg width="400" height="400"> </svg>
</div>
```
```
/* xxx.css */
.container{
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: #F1F3F5;
}
svg{
background-color: blue;
}
```
![en-us_image_0000001232162324](figures/en-us_image_0000001232162324.png)
## Setting Attributes
Set the **width**, **height**, **x**, **y**, and **viewBox** attributes to define the width, height, X coordinate, Y coordinate, and SVG viewport of the **&lt;svg&gt;** component.
```
<!-- xxx.hml -->
<div class="container">
<svg width="400" height="400" viewBox="0 0 100 100">
<svg class="rect" width="100" height="100" x="20" y="10">
</svg>
</svg>
</div>
```
```
/* xxx.css */
.container{
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: #F1F3F5;
}
svg{
background-color: yellow;
}
.rect{
background-color: red;
}
```
![en-us_image_0000001231683152](figures/en-us_image_0000001231683152.png)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> - If the **&lt;svg&gt;** component is the root node, the X-axis and Y-axis attributes are invalid.
>
> - If the width and height of **viewBox** are inconsistent with those of the **&lt;svg&gt;** component, the view box will be scaled in center-aligned mode.
# Path Drawing
The **&lt;svg&gt;** component uses instructions **M** (start point), **H** (horizontal line), and **a** (drawing an arc to a specified position) to control a path and sets the fill colors to create a pie chart.
```
<!-- xxx.hml -->
<div class="container">
<svg fill="#00FF00" x="100" y="400">
<path d="M300,200 h-150 a150 150 0 1 0 150 -150 z" fill="red" stroke="blue" stroke-width="5" >
</path>
<path d="M275,175 v-150 a150 150 0 0 0 -150 150 z" fill="yellow" stroke="blue" stroke-width="5">
</path>
</svg>
</div>
```
```
/* xxx.css */
.container {
flex-direction: row;
justify-content: flex-start;
align-items: flex-start;
height: 1200px;
width: 600px;
background-color: #F1F3F5;
}
```
![en-us_image_0000001232162340](figures/en-us_image_0000001232162340.png)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> - M/m = moveto The **x** and **y** parameters indicate the destination X and Y coordinates of a point. The **M** command only moves the brush, but does not draw a line between two points. Therefore, the **M** command is often used at the beginning of a path to indicate the start point.
>
> - L/l = lineto The **x** and **y** parameters indicate the X and Y coordinates of a point. The **L** command draws a line between the current position and the destination position (the previous point of the brush).
>
> - H/h = horizontal lineto Draws a horizontal line.
>
> - V/v = vertical lineto Draws a vertical line.
>
> - C/c = curveto Draws a cubic Bezier curve. Three groups of coordinate parameters are required: **x1 y1**, **x2 y2**, **x y**.
>
> - S/s = smooth curveto Draws a cubic Bezier curve. Two groups of coordinate parameters are required: **x2 y2**, **x y**.
>
> - Q/q = quadratic Belzier curve Draws a quadratic Bezier curve. Two groups of coordinate parameters are required: **x1 y1**, **x y**.
>
> - T/t = smooth quadratic Belzier curveto Draws a quadratic Bezier curve. One group of coordinate parameters are required: **x y**.
>
> - A/a = elliptical Arc Draw an arc. The following parameters are required: **rx ry x-axis-rotation** (rotation angle), **large-arc-flag** (angle), **sweep-flag** (arc direction), and **x y**. **large-arc-flag** determines whether the arc is less than 180 degrees. **0** indicates yes, and **1** indicates no. **sweep-flag** indicates the direction in which an arc is drawn. **0** indicates that the arc is drawn counterclockwise from the start point to the end point. **1** indicates that the arc is drawn clockwise from the start point to the end point.
>
> - Z/z = closepath Draws a straight line from the current point to the start point of the path.
# Text Drawing
The **&lt;svg&gt;** component can also be used to draw text.
## Text
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> - The text content must be written in the **&lt;text&gt;** area. The **&lt;tspan&gt;** child element label can be nested.
>
> - **&lt;text&gt;** can be nested only by the parent element label **svg**.
>
> - Only the default font **sans-serif** is supported.
Set the following attributes to define text styles: **x** (X coordinate), **y** (Y coordinate), **dx** (x-axis offset of the text), **dy** (y-axis offset of the text), **fill** (font fill color), **stroke** (text border color), and **stroke-width** (text border width).
```
<!-- xxx.hml -->
<div class="container">
<svg>
<text x="200" y="300" font-size="80px" fill="blue" >Hello World</text>
<text x="200" y="300" dx="20" dy="80" font-size="80px" fill="blue" fill-opacity="0.5" stroke="red" stroke-width="2">Hello World</text>
<text x="20" y="550" fill="#D2691E">
<tspan dx="40" fill="red" font-size="80" fill-opacity="0.4">Hello World </tspan>
</text>
</svg>
</div>
```
![en-us_image_0000001275803145](figures/en-us_image_0000001275803145.png)
## Drawing Text Along the Path
Set **textpath** to draw text along the path.
```
<!-- xxx.hml -->
<div class="container">
<svg fill="#00FF00" x="100" y="400">
<path d="M40,360 Q360,360 360,180 Q360,20 200,20 Q40,40 40,160 Q40,280 180,180 Q180,180 200,100" stroke="red" fill="none"></path>
<text>
<textpath fill="blue" startOffset="20%" path="M40,360 Q360,360 360,180 Q360,20 200,20 Q40,40 40,160 Q40,280 180,180 Q180,180 200,100" font-size="30px">
This is textpath test.
</textpath>
</text>
</svg>
</div>
```
![en-us_image_0000001231843084](figures/en-us_image_0000001231843084.png)
# &lt;swiper&gt; Development
The **&lt;swiper&gt;** component is a sliding container used to switch between child components. For details, see [swiper](../reference/arkui-js/js-components-container-swiper.md).
## Creating a &lt;swiper&gt; Component
Create a **&lt;swiper&gt;** component in the .hml file under **pages/index**.
```
<!-- xxx.hml-->
<div class="container">
<swiper>
<div class="item" style="background-color: #bf45ea;">
<text>item1</text>
</div>
<div class="item" style="background-color: #088684;">
<text>item2</text>
</div>
<div class="item" style="background-color: #7786ee;">
<text>item3</text>
</div>
</swiper>
</div>
```
```
/* xxx.css */
.container{
width: 100%;
height: 100%;
flex-direction: column;
background-color: #F1F3F5;
align-items: center;
justify-content: center;
width: 100%;
}
swiper{
height: 30%;
}
.item{
width: 100%;
height: 500px;
}
text{
width: 100%;
height: 100%;
text-align: center;
font-size: 50px;
color: white;
}
```
![en-us_image_0000001232003028](figures/en-us_image_0000001232003028.gif)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> The **&lt;swiper&gt;** component supports child components except **&lt;list&gt;**.
## Adding Attributes
When **loop** is set to **false**, the **autoplay** attribute is added to the **&lt;swiper&gt;** component and the autoplay interval (**interval**) is set. The component automatically switches between child components and stops at the last one. Add the **digital** attribute to enable the digital navigation point and set **scrolleffect** to **fade**.
```
<!-- xxx.hml-->
<div class="container">
<swiper index="1" autoplay="true" interval="2000" indicator="true" digital="true" duration="500"
scrolleffect="fade" loop="false">
<div class="item" style="background-color: #bf45ea;">
<text>item1</text>
</div>
<div class="item" style="background-color: #088684;">
<text>item2</text>
</div>
<div class="item" style="background-color: #7786ee;">
<text>item3</text>
</div>
<div class="item" style="background-color: #c88cee;">
<text>item4</text>
</div>
</swiper>
</div>
```
```
/* xxx.css */
.container{
width: 100%;
height: 100%;
flex-direction: column;
background-color: #F1F3F5;
align-items: center;
justify-content: center;
width: 100%;
}
swiper{
height: 30%;
}
.item{
width: 100%;
height: 500px;
}
text{
width: 100%;
height: 100%;
text-align: center;
font-size: 50px;
color: white;
}
```
![en-us_image_0000001275923021](figures/en-us_image_0000001275923021.gif)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> - The **digital** attribute takes effect only when the **indicator** attribute is set to **true**.
>
> - The **loop** attribute takes effect only when there are two or more than two child components of the **&lt;swiper&gt;** component.
>
> - The **scrolleffect** attribute takes effect only when the **loop** attribute value is set to **false**.
## Setting Styles
Set the width and height of the **&lt;swiper&gt;** component, the indicator's size (**indicator-size**), color (**indicator-color**), relative position (**indicator-top**), and color when it is selected (**indicator-selected-color**).
```
<!-- xxx.hml-->
<div class="container">
<swiper index="1" autoplay="true" interval="2000" duration="500" >
<div class="item" style="background: linear-gradient(to right,#806dd9,#5d44ea,#2eb9d5)">
<text>item1</text>
</div>
<div class="item" style="background: linear-gradient( to right,#2eb9d5,#0e7db4,#2673d9)">
<text>item2</text>
</div>
<div class="item" style="background: linear-gradient( to right,#2673d9,#0c89af,#806dd9)">
<text>item3</text>
</div>
</swiper>
</div>
```
```
/* xxx.css */
.container{
flex-direction: column;
background-color: #F1F3F5;
align-items: center;
justify-content: center;
width: 100%;
}
swiper{
width: 500px;
height: 500px;
border-radius: 250px;
indicator-color: white;
indicator-selected-color: blue;
indicator-size: 40px;
indicator-top: 100px;
overflow: hidden ;
}
.item{
width: 100%;
height: 500px;
}
text{
width: 100%;
text-align: center;
margin-top: 150px;
font-size: 50px;
color: white;
}
```
![en-us_image_0000001275803189](figures/en-us_image_0000001275803189.gif)
## Binding Events
Create two **&lt;text&gt;** components and bind click events. Clicking the component will call **showPrevious** to display the previous child component or **showNext** to display the next child component. Add a **&lt;select&gt;** component. A **change** event is triggered when a user selects a value from the drop-down list box and the **swipeTo** method is called to go to the specified page. Bind the **&lt;swiper&gt;** component with the **change** event (triggered when the index of the currently displayed component changes) and the **finish** event (triggered when the switchover animation ends).
```
<!-- xxx.hml-->
<div class="container">
<swiper interval="2000" onchange="change" loop="false" onanimationfinish="finish" id="swiper">
<div class="item" style="background-color: #bf45ea">
<text>item1</text>
</div>
<div class="item" style="background-color: #088684;">
<text>item2</text>
</div>
<div class="item" style="background-color: #7786ee;">
<text>item3</text>
</div>
<div class="item" style="background-color: #c88cee;">
<text>item4</text>
</div>
</swiper>
<div class="content">
<button class="pnbtn" onclick="previous">Previous</button>
<select onchange="selectChange">
<option value="0">swipeTo 1</option>
<option value="1">swipeTo 2</option>
<option value="2">swipeTo 3</option>
<option value="3">swipeTo 4</option>
</select>
<button class="pnbtn" onclick="next">Next</button>
</div>
</div>
```
```
/* xxx.css */
.container{
width: 100%;
height: 100%;
flex-direction: column;
background-color: #F1F3F5;
align-items: center;
justify-content: center;
width: 100%;
}
swiper{
height: 30%;
}
.item{
width: 100%;
height: 500px;
}
text{
width: 100%;
height: 100%;
text-align: center;
font-size: 50px;
color: white;
}
select{
background-color: white;
width: 250px;
height: 80px;
}
.content{
margin-top: 100px;
justify-content: space-around;
}
.pnbtn{
width: 200px;
height: 80px;
font-size: 30px;
}
```
```
import prompt from '@system.prompt';
export default{
change(e){
prompt.showToast({duration:2000,message:"current index:"+e.index});
},
finish(){
prompt.showToast({duration:2000,message:"The switchover ends"});
},
selectChange(e){
this.$element('swiper').swipeTo({index: Number(e.newValue)});
},
previous(){
this.$element('swiper').showPrevious();
},
next(){
this.$element('swiper').showNext();
}
}
```
![en-us_image_0000001231843128](figures/en-us_image_0000001231843128.gif)
## Example Scenario
Use the **&lt;swiper&gt;** component to create an image carousel and a thumbnail module at the bottom of the carousel. After a thumbnail is clicked, the **swipeTo** method is called to switch to the corresponding image.
```
<!-- xxx.hml-->
<div class="container">
<swiper duration="500" indicator="false" id="swiper" onchange="change">
<div class="item" for="item in list">
<image src="{{item.src}}"></image>
</div>
</swiper>
<div class="content">
<div class="content_item {{index == $idx?'actived':''}}" for="item in list" onclick="imageTo({{$idx}})">
<image src="{{item.src}}"></image>
</div>
</div>
</div>
```
```
/* xxx.css */
.container{
flex-direction: column;
background-color: #F1F3F5;
align-items: center;
justify-content: center;
width: 100%;
}
swiper{
width: 100%;
height: 500px;
}
.item{
width: 100%;
height: 500px;
}
.content{
margin-top: -120px;
width: 70%;
display: flex;
justify-content: space-around;
height: 100px;
}
.content_item{
padding: 5px;
transform: scale(0.5);
}
.actived{
transform: scale(1);
border: 1px solid #b20937ea;
}
```
```
// index.js
import prompt from '@system.prompt';
export default {
data:{
index: 0,
list:[
{src: 'common/images/1.png'},
{src: 'common/images/2.png'},
{src: 'common/images/3.png'},
{src: 'common/images/4.png'},]
},
imageTo(index){
this.index = index;
this.$element('swiper').swipeTo({index: index});
},
change(e){
this.index = e.index;
}
}
```
![en-us_image_0000001231843132](figures/en-us_image_0000001231843132.gif)
# &lt;switch&gt; Development
The **&lt;switch&gt;** component is used to switch between the on and off states. For details, see [switch](../reference/arkui-js/js-components-basic-switch.md).
## Creating a &lt;switch&gt; Component
Create a **&lt;switch&gt;** component in the .hml file under **pages/index**.
```
<div class="container">
<switch></switch>
</div>
```
```
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
```
![en-us_image_0000001231843096](figures/en-us_image_0000001231843096.png)
## Adding Attributes and Methods
Use the **textoff** and **showtext** attributes to set the status when text is selected and unselected. Set the **checked** attribute to **true** (indicating that the component is on). Add the **change** event that is triggered when the component status changes. After the event is triggered, the **switchChange** function is executed to obtain the current component status (on or off).
```
<!-- xxx.hml -->
<div class="container">
<switch showtext="true" texton="open" textoff="close" checked="true" @change="switchChange"></switch>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
switch{
// Color of the selected text
texton-color: #002aff;
// Color of the unselected text
textoff-color: silver;
text-padding: 20px;
font-size: 50px;
}
```
```
// xxx.js
import prompt from '@system.prompt';
export default {
switchChange(e){
if(e.checked){
prompt.showToast({
message: "open"
});
}else{
prompt.showToast({
message: "close"
});
}
}
}
```
![en-us_image_0000001276003505](figures/en-us_image_0000001276003505.gif)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> The text set by **texton** and **textoff** takes effect only when **showtext** is set to **true**.
## Example Scenario
Turn on the switch and the default delivery address is used. When the switch is turned off, the address selection button is displayed on the page. Clicking the button can change the delivery address.
Implementation method: Create a **&lt;switch&gt;** component, set the **checked** attribute to **true**, and change the delivery address through data binding. Set the **display** attribute (the default value is **none**). When the switch is turned off and the **display** attribute is set to **flex**, the address module is displayed and clicking the button can change the color.
```
<!-- xxx.hml -->
<div class="container">
<div class="change">
<text>Choose default address:</text>
<switch showtext="true" texton="on" textoff="off" checked="true" @change="switchChange"></switch>
</div>
<div class="content">
<text class="address"><span>Shipping address:</span><span class="textSpan">{{address}}</span></text>
</div>
<div class="myAddress" style="display: {{addressDisplay}};">
<text style="font-size: 30px;margin-bottom: 50px;">Choose an address:</text>
<text class="addressText" style="background-color: {{item == address?'#0fabe7':''}};color: {{item == address?'white':'black'}};"
for="item in addressList"@click="changeAddress({{$idx}}})">{{item}}</text>
</div>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
background-color: #F1F3F5;
flex-direction: column;
padding: 50px;
}
.change{
margin-top: 20%;
width: 100%;
justify-content: center;
}
switch{
texton-color: #002aff;
textoff-color: silver;
text-padding: 20px;
}
.content{
width: 70%;
text-align: center;
flex-direction: column;
border: 1px solid #002aff;
margin-left: 15%;
text-align: center;
}
.address{
width: 100%;
height: 100px;
line-height: 100px;
text-align: center;
font-size: 28px;
margin-bottom: 50px;
}
.textSpan{
color: #0aa9f1;
}
.myAddress{
flex-direction: column;
margin-top: 50px;
}
.addressText{
margin-left: 35%;
width: 30%;
height: 75px;
text-align: center;
color: white;
margin-bottom: 30px;
border-radius: 10px;
border: 1px solid #0fabe7;
}
```
```
// xxx.js
import prompt from '@system.prompt';
export default {
data:{
address: '',
addressDisplay: 'none',
addressList: ['family','company','commissary'],
},
onInit(){
// Initialize the default address to the first one in the address list.
this.address = this.addressList[0];
},
switchChange(e){
if(e.checked){
this.addressDisplay = "none";
}else{
this.addressDisplay = "flex";
}
},
changeAddress(i){
this.address= this.addressList[i];
}
}
```
![en-us_image_0000001231843100](figures/en-us_image_0000001231843100.gif)
# &lt;text&gt; Development # &lt;text&gt; Development
The &lt;text&gt; component is used to display a piece of textual information. For details, see [text](../reference/arkui-js/js-components-basic-text.md). The **&lt;text&gt;** component is used to display a piece of textual information. For details, see [text](../reference/arkui-js/js-components-basic-text.md).
## Creating a &lt;text&gt; Component ## Creating a &lt;text&gt; Component
Create a &lt;text&gt; component in the .hml file under pages/index. Create a **&lt;text&gt;** component in the .hml file under **pages/index**.
``` ```
<!-- xxx.hml --> <!-- xxx.hml -->
<div class="container" style="text-align: center;justify-content: center; align-items: center;"> <div class="container" style="text-align: center;justify-content: center; align-items: center;">
<text>Hello World</text> <text>
Hello World
</text>
</div> </div>
``` ```
...@@ -35,10 +37,9 @@ Create a &lt;text&gt; component in the .hml file under pages/index. ...@@ -35,10 +37,9 @@ Create a &lt;text&gt; component in the .hml file under pages/index.
## Setting the Text Style and Attributes ## Setting the Text Style and Attributes
- Adding a text style - Adding a text style
Set the color, font-size, allow-scale, word-spacing and text-align properties to add the color, size, zoom, text spacing, and vertical alignment of the text.
Set the color, font-size, allow-scale, word-spacing, and text-valign attributes to apply the color, size, zoom, spacing, and vertical alignment styles to the text.
``` ```
<!-- xxx.hml --> <!-- xxx.hml -->
<div class="container" style="background-color:#F1F3F5;flex-direction: column;justify-content: center; align-items: center;"> <div class="container" style="background-color:#F1F3F5;flex-direction: column;justify-content: center; align-items: center;">
...@@ -52,7 +53,6 @@ Create a &lt;text&gt; component in the .hml file under pages/index. ...@@ -52,7 +53,6 @@ Create a &lt;text&gt; component in the .hml file under pages/index.
``` ```
``` ```
/* xxx.css */ /* xxx.css */
.container { .container {
...@@ -65,14 +65,13 @@ Create a &lt;text&gt; component in the .hml file under pages/index. ...@@ -65,14 +65,13 @@ Create a &lt;text&gt; component in the .hml file under pages/index.
} }
``` ```
![en-us_image_0000001222967764](figures/en-us_image_0000001222967764.png)
![en-us_image_0000001222967764](figures/en-us_image_0000001222967764.png)
- Adding a text modifier - Adding a text modifier
Set the **text-decoration** and **text-decoration-color** attributes to add an underline, overline, line-through, or a combination of lines in the specified color to selected text. For values of **text-decoration**, see [Text Style](../reference/arkui-js/js-components-basic-text.md).
Set the text-decoration attribute to add a line to selected text. Set the text-decoration-color attribute to apply specific color to the added line. For values of text-decoration, see [Text Style](../reference/arkui-js/js-components-basic-text.md).
``` ```
<!-- xxx.hml --> <!-- xxx.hml -->
<div class="container" style="background-color:#F1F3F5;"> <div class="container" style="background-color:#F1F3F5;">
...@@ -85,6 +84,7 @@ Create a &lt;text&gt; component in the .hml file under pages/index. ...@@ -85,6 +84,7 @@ Create a &lt;text&gt; component in the .hml file under pages/index.
</div> </div>
``` ```
``` ```
/* xxx.css */ /* xxx.css */
.container { .container {
...@@ -99,14 +99,13 @@ Create a &lt;text&gt; component in the .hml file under pages/index. ...@@ -99,14 +99,13 @@ Create a &lt;text&gt; component in the .hml file under pages/index.
} }
``` ```
![en-us_image_0000001223287688](figures/en-us_image_0000001223287688.png) ![en-us_image_0000001223287688](figures/en-us_image_0000001223287688.png)
- Hiding text content
Set the text-overflow attribute to ellipsis so that overflowed text is displayed as an ellipsis. - Hiding text content
Set the **text-overflow** attribute to **ellipsis** so that overflowed text is displayed as an ellipsis.
``` ```
<!-- xxx.hml --> <!-- xxx.hml -->
<div class="container"> <div class="container">
...@@ -116,6 +115,7 @@ Create a &lt;text&gt; component in the .hml file under pages/index. ...@@ -116,6 +115,7 @@ Create a &lt;text&gt; component in the .hml file under pages/index.
</div> </div>
``` ```
``` ```
/* xxx.css */ /* xxx.css */
.container { .container {
...@@ -129,25 +129,22 @@ Create a &lt;text&gt; component in the .hml file under pages/index. ...@@ -129,25 +129,22 @@ Create a &lt;text&gt; component in the .hml file under pages/index.
.text{ .text{
width: 200px; width: 200px;
max-lines: 1; max-lines: 1;
text-overflow:ellipsis; text-overflow:ellipsis;
} }
``` ```
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> - **text-overflow** must be used together with **max-lines**.
>
> - **max-lines** indicates the maximum number of lines in the text.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: ![en-us_image_0000001267647865](figures/en-us_image_0000001267647865.png)
> - text-overflow must be used together with max-lines.
>
> - max-lines indicates the maximum number of lines in the text.
![en-us_image_0000001267647865](figures/en-us_image_0000001267647865.png)
- Setting the text line breaking mode - Setting the text line breaking mode
Set the **word-break** attribute to specify how to break lines of text. For values of **word-break**, see [Text Styles](../reference/arkui-js/js-components-basic-text.md).
Set the word-break attribute to specify how to break lines of text. For values of word-break, see [Text Styles](../reference/arkui-js/js-components-basic-text.md).
``` ```
<!-- xxx.hml --> <!-- xxx.hml -->
<div class="container"> <div class="container">
...@@ -162,6 +159,7 @@ Create a &lt;text&gt; component in the .hml file under pages/index. ...@@ -162,6 +159,7 @@ Create a &lt;text&gt; component in the .hml file under pages/index.
</div> </div>
``` ```
``` ```
/* xxx.css */ /* xxx.css */
.container { .container {
...@@ -188,66 +186,74 @@ Create a &lt;text&gt; component in the .hml file under pages/index. ...@@ -188,66 +186,74 @@ Create a &lt;text&gt; component in the .hml file under pages/index.
height: 200px; height: 200px;
border:1px solid #0931e8; border:1px solid #0931e8;
text-align: center; text-align: center;
word-break: break-all; word-break: break-all;
font-size: 40px; font-size: 40px;
} }
``` ```
![en-us_image_0000001267767865](figures/en-us_image_0000001267767865.png)
![en-us_image_0000001267767865](figures/en-us_image_0000001267767865.png)
- Setting the [&lt;span&gt;](../reference/arkui-js/js-components-basic-span.md)child component
``` - Setting the [&lt;span&gt;](../reference/arkui-js/js-components-basic-span.md) child component.
<!-- xxx.hml -->
<div class="container" style="justify-content: center; align-items: center;flex-direction: column;background-color: #F1F3F5;"> ```
<text style="font-size: 45px;"> <!-- xxx.hml -->
This is a passage <div class="container" style="justify-content: center; align-items: center;flex-direction: column;background-color: #F1F3F5; width: 100%;height: 100%;">
</text> <text style="font-size: 45px;">
<text style="font-size: 45px;"> This is a passage
<span style="color: aqua;">This </span><span style="color: #F1F3F5;"> 1 </span> <span style="color: blue;"> is a </span> <span style="color: #F1F3F5;"> 1 </span> <span style="color: red;"> passage </span> </text>
</text> <text style="font-size: 45px;">
</div> <span style="color: aqua;">This </span>
``` <span style="color: #F1F3F5;">
1
</span>
<span style="color: blue;"> is a </span>
<span style="color: #F1F3F5;">
1
</span>
<span style="color: red;"> passage </span>
</text>
</div>
```
![en-us_image_0000001223127720](figures/en-us_image_0000001223127720.png)
![en-us_image_0000001223127720](figures/en-us_image_0000001223127720.png) > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> - When the **&lt;span&gt;** child component is used to form a text paragraph, incorrect **&lt;span&gt;** attribute settings (for example, setting of **font-weight** to **1000**) will result in abnormal display of the text paragraph.
>
> - When the **&lt;span&gt;** child component is being used, do not include any text you want to show in the **&lt;text&gt;** component, as such text will not be displayed if you do so.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: ## Example Scenario
> - When the &lt;span&gt; child component is used to form a text paragraph, incorrect &lt;span&gt; attribute settings (for example, setting of font-weight to 1000) will result in abnormal display of the text paragraph.
>
> - When the &lt;span&gt; child component is being used, do not include any text you want to show in the &lt;text&gt; component, as such text will not be displayed if you do so.
Use the **&lt;text&gt;** component to display text content through data binding. Use the **&lt;span&gt;** child component to hide or display text content by setting the **show** attribute.
## Example Scenario
Use the &lt;text&gt; component to display text content through data binding. Use the &lt;span&gt; child component to hide or display text content by setting the show attribute. ```
<!-- xxx.hml -->
<div class="container">
``` <div style="align-items: center;justify-content: center;">
<!-- xxx.hml --> <text class="title">
<div class="container"> {{ content }}
<div style="align-items: center;justify-content: center;"> </text>
<text class="title"> <switch checked="true" onchange="test"></switch>
{{ content }} </div>
</text> <text class="span-container" style="color: #ff00ff;">
<switch checked="true" onchange="test"></switch> <span show="{{isShow}}"> {{ content }} </span>
</div> <span style="color: white;">
<text class="span-container" style="color: #ff00ff;"> 1
<span show="{{isShow}}"> {{ content }} </span> </span>
<span style="color: white;"> <span style="color: #f76160">Hide clip </span>
1 </text>
</span> </div>
<span style="color: #f76160">Hide clip </span> ```
</text>
</div>
```
``` ```
/* xxx.css */ /* xxx.css */
.container { .container {
width: 100%;
height: 100%;
align-items: center; align-items: center;
flex-direction: column; flex-direction: column;
justify-content: center; justify-content: center;
...@@ -266,7 +272,7 @@ Use the &lt;text&gt; component to display text content through data binding. Use ...@@ -266,7 +272,7 @@ Use the &lt;text&gt; component to display text content through data binding. Use
// xxx.js // xxx.js
export default { export default {
data: { data: {
isShow:true, isShow:true,
content: 'Hello World' content: 'Hello World'
}, },
onInit(){ }, onInit(){ },
......
# &lt;toolbar&gt; Development
The **&lt;toolbar&gt;** component shows actions available on the current screen and can be used for level-1 navigation. For details, see [toolbar](../reference/arkui-js/js-components-basic-toolbar.md).
## Creating a &lt;toolbar&gt; Component
Create a **&lt;toolbar&gt;** component in the .hml file under **pages/index**.
```
<!-- xxx.hml -->
<div class="container">
<toolbar style="background-color: #F1F3F5;">
<toolbar-item value="item1"></toolbar-item>
<toolbar-item value="item2"></toolbar-item>
</toolbar>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
toolbar-item{
font-size: 35px;
}
```
![en-us_image_0000001275922977](figures/en-us_image_0000001275922977.gif)
## Add Child Components
The **&lt;toolbar&gt;** component supports only the **&lt;toolbar-item&gt;** child component and can display a maximum of five **&lt;toolbar-item&gt;** child components on a page. If there are six or more **&lt;toolbar-item&gt;** child components, the first four child components are retained, and the rest are moved to the **More** option on the toolbar and can be displayed on a pop-up window by clicking **More**. Under **More**, the child components are displayed in the default style; the custom style settings do not take effect.
```
<!-- xxx.hml -->
<div class="container">
<toolbar>
<toolbar-item value="item1"></toolbar-item>
<toolbar-item value="item2"></toolbar-item>
<toolbar-item value="item3"></toolbar-item>
<toolbar-item value="item4"></toolbar-item>
<toolbar-item value="item5"></toolbar-item>
<toolbar-item value="item6"></toolbar-item>
</toolbar>
</div>
```
```
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
toolbar-item{
font-size: 35px;
}
```
![en-us_image_0000001232002988](figures/en-us_image_0000001232002988.gif)
## Setting Styles
Set the **position** style for the **&lt;toolbar&gt;** component and set the font color, size, and background color of **&lt;toolbar-item&gt;** child components.
```
<!-- xxx.hml -->
<div class="container">
<toolbar style="position: fixed;bottom: 5%;width: 100%;background-color: #F1F3F5;">
<toolbar-item value="item1" icon="common/images/1.png" class="toolbarActive"></toolbar-item>
<toolbar-item value="item2" icon="common/images/2.png"></toolbar-item>
<toolbar-item value="item3" icon="common/images/1.png"></toolbar-item>
<toolbar-item value="item4" icon="common/images/2.png"></toolbar-item>
</toolbar>
</div>
```
```
/* xxx.css */
.container {
background-color: #F1F3F5;
flex-direction: column;
width: 100%;
justify-content: center;
align-items: center;
}
toolbar-item{
font-size: 35px;
}
.toolbarActive{
color: red;
background-color: #daebef;
}
```
![en-us_image_0000001275803149](figures/en-us_image_0000001275803149.png)
## Binding Events
Bind the click event and long press event to the **&lt;toolbar-item&gt;** child components, so that the text of these components turns red upon click and turns blue upon long press.
```
<!-- xxx.hml -->
<div class="container">
<toolbar style="position: fixed;top: 50%;width: 100%;background-color: #F1F3F5;">
<toolbar-item value="item1" icon="common/images/1.png" style="color: {{itemColor}};" onclick="itemClick"></toolbar-item>
<toolbar-item value="item2" icon="common/images/2.png" style="color: {{itemColor}}"></toolbar-item>
<toolbar-item value="item3" icon="common/images/3.png" style="color: {{itemColor}}" onlongpress="itemLongPress"></toolbar-item>
</toolbar>
</div>
```
```
/* xxx.css */
.container {
background-color: #F1F3F5;
flex-direction: column;
width: 100%;
justify-content: center;
align-items: center;
}
toolbar-item{
font-size: 35px;
}
```
```
// xxx.js
import prompt from '@system.prompt';
export default {
data:{
itemColor:'black'
},
itemClick(){
this.itemColor= "red";
prompt.showToast({duration:2000,message:'item click'});
},
itemLongPress(){
prompt.showToast({duration:2000,message:'item long press'});
this.itemColor= "blue";
},
}
```
![en-us_image_0000001275803153](figures/en-us_image_0000001275803153.gif)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
> The **&lt;toolbar&gt;** component does not allow adding of events or methods, but its child components do.
## Example Scenario
In this example, you'll implement a **&lt;toolbar-item&gt;** component, clicking which will trigger a change in the text color and the image corresponding to the component.
Use the **for** loop to create a **&lt;toolbar-item&gt;** component and bind a click event to it, so that clicking the component will obtain and store an index value. When setting the text color, the system checks whether the current index value is the stored value. If yes, the system sets the color to red. If no, the system uses the default color.
```
<!-- xxx.hml -->
<div class="container">
<image src="{{imgList[active]}}"></image>
<toolbar style="position: fixed;bottom: 5%;width: 100%;background-color: #F1F3F5;">
<toolbar-item value="{{ item.option}}" icon="{{item.icon}}" style="color: {{active == $idx?'red':'black'}};background-color: {{active
== $idx?'#dbe7f1':'#F1F3F5'}};" for="{{item in itemList}}" onclick="itemClick({{$idx}})"></toolbar-item>
</toolbar>
</div>
```
```
/* xxx.css */
.container {
background-color: #F1F3F5;
flex-direction: column;
width: 100%;
justify-content: center;
align-items: center;
}
toolbar-item{
font-size: 35px;
}
```
```
// xxx.js
import prompt from '@system.prompt';
export default {
data:{
active: 0,
imgList:["common/images/1.png","common/images/2.png","common/images/3.png","common/images/4.png"],
itemList:[
{option:'item1',icon:'common/images/1.png'},
{option:'item2',icon:'common/images/2.png'},
{option:'item3',icon:'common/images/3.png'},
{option:'item4',icon:'common/images/4.png'},
]
},
itemClick(id){
this.active= id;
},
}
```
![en-us_image_0000001231683128](figures/en-us_image_0000001231683128.gif)
# Button
The **\<Button>** component is usually activated by user clicks to perform a specific action, for example, submitting a form. Buttons are classified as capsule, circle, or normal buttons.
## Creating a Button
You can create a button by invoking either of the following APIs:
- Button(options?: {type?: ButtonType, stateEffect?: boolean})
This API creates a button that contains child components. In the syntax, **type** indicates the button type, and **stateEffect** indicates whether to enable the click effect for the button.
```
Button({ type: ButtonType.Normal, stateEffect: true }) {
Row() {
Image($r('app.media.loading')).width(20).height(20).margin({ left: 12 })
Text('loading').fontSize(12).fontColor(0xffffff).margin({ left: 5, right: 12 })
}.alignItems(VerticalAlign.Center)
}.borderRadius(8).backgroundColor(0x317aff).width(90)
```
![en-us_image_0000001260555857](figures/en-us_image_0000001260555857.png)
- Button(label?: string, options?: { type?: ButtonType, stateEffect?: boolean })
This API creates a button that does not contain any child components. In the syntax, **label** indicates whether the created button contains child components.
```
Button('Ok', { type: ButtonType.Normal, stateEffect: true })
.borderRadius(8)
.backgroundColor(0x317aff)
.width(90)
```
![en-us_image_0000001215796030](figures/en-us_image_0000001215796030.png)
## Setting the Button Type
Use the **type** parameter to set the button type to **Capsule**, **Circle**, or **Normal**.
- Capsule button (default type)
```
Button('Disable', { type: ButtonType.Capsule, stateEffect: false })
.backgroundColor(0x317aff)
.width(90)
```
![en-us_image_0000001215645452](figures/en-us_image_0000001215645452.png)
- Circle button
```
Button('Circle', { type: ButtonType.Circle, stateEffect: false })
.backgroundColor(0x317aff)
.width(90)
.height(90)
```
![en-us_image_0000001215965420](figures/en-us_image_0000001215965420.png)
## Setting Styles
- Set the border radius:
In general cases, you can use universal attributes to define the button styles. For example, you can use the **borderRadius** attribute to set the border radius.
```
Button('circle border', { type: ButtonType.Normal })
.borderRadius(20)
```
![zh-cn_image_0000001190463780](figures/zh-cn_image_0000001190463780.png)
- Setting Text Styles
Add a font style for text displayed on the button.
```
Button('font style', { type: ButtonType.Normal })
.fontSize(20)
.fontColor(Color.Red)
.fontWeight(800)
```
![zh-cn_image_0000001189744672](figures/zh-cn_image_0000001189744672.png)
- Set the background color:
You can do so by adding the **backgroundColor** attribute.
```
Button('background color').backgroundColor(0xF55A42)
```
![en-us_image_0000001235146483](figures/en-us_image_0000001235146483.png)
- Assign a function to the button:
In this example, we are creating a button with the delete function.
```
Button({ type: ButtonType.Circle, stateEffect: true }) {
Image($r('app.media.ic_public_delete_filled')).width(30).height(30)
}.width(55).height(55).margin({ left: 20 }).backgroundColor(0xF55A42)
```
![en-us_image_0000001260373911](figures/en-us_image_0000001260373911.png)
## Adding Events
The **\<Button>** component is usually used to trigger actions. You can bind the **onClick** event to the button to have it respond with custom behavior after being clicked.
```
Button('Ok', { type: ButtonType.Normal, stateEffect: true })
.onClick(()=>{
console.info('Button onClick')
})
```
## Example Scenarios
- Using the Button for Startup
You can use the button for any UI element that involves the startup operation. The button triggers the predefined event based on the user's operation. For example, you can use a button in the **\<List>** container to redirect the user to another page.
```
import router from '@ohos.router'
@Entry
@Component
struct ButtonCase1 {
build() {
List({ space: 4 }) {
ListItem() {
Button("First").onClick(() => {
router.push({ url: 'xxx' })
})
}
ListItem() {
Button("Second").onClick(() => {
router.push({ url: 'yyy' })
})
}
ListItem() {
Button("Third").onClick(() => {
router.push({ url: 'zzz' })
})
}
}
.listDirection(Axis.Vertical)
.backgroundColor(0xDCDCDC).padding(20)
}
}
```
![en-us_image_0000001235626467](figures/en-us_image_0000001235626467.png)
- Using the Button for Submitting Forms
On the user login/registration page, you can use a button to submit a login or registration request.
```
@Entry
@Component
struct ButtonCase2 {
build() {
Column() {
TextInput({ placeholder: 'input your username' }).margin({ top: 20 })
TextInput({ placeholder: 'input your password' }).type(InputType.Password).margin({ top: 20 })
Button('Register').width(300).margin({ top: 20 })
}.padding(20)
}
}
```
![en-us_image_0000001190466492](figures/en-us_image_0000001190466492.png)
# Web # Web
The \<Web> component can be used to display web pages. For details, see [Web API](../reference/arkui-ts/ts-basic-components-web.md). The **\<Web>** component can be used to display web pages. For details, see [Web API](../reference/arkui-ts/ts-basic-components-web.md).
## Creating a Component ## Creating a Component
Create a \<Web> component in the .ets file under main/ets/MainAbility/pages. Then, in the created component, use src to specify the web page URI to be referenced, and bind a controller to the component to call the component APIs. Create a **\<Web>** component in the .ets file under **main/ets/MainAbility/pages**. Then, in the created component, use **src** to specify the web page URI to be referenced, and bind a controller to the component to call the component APIs.
``` ```
// xxx.ets // xxx.ets
...@@ -22,7 +22,7 @@ Create a \<Web> component in the .ets file under main/ets/MainAbility/pages. The ...@@ -22,7 +22,7 @@ Create a \<Web> component in the .ets file under main/ets/MainAbility/pages. The
## Setting Styles and Attributes ## Setting Styles and Attributes
When using the \<Web> component, you need to specify the styles and attributes. The sample code is as follows. When using the **\<Web>** component, you need to specify the styles and attributes. The sample code is as follows.
``` ```
// xxx.ets // xxx.ets
...@@ -50,7 +50,7 @@ struct WebComponent { ...@@ -50,7 +50,7 @@ struct WebComponent {
``` ```
## Adding Events and Methods ## Adding Events and Methods
Add the onProgressChange event for the \<Web> component, which is triggered when the loading progress changes and returns the progress value in its callback. Assign the progress value to the \<Progress> component to control the status of the component. When the progress reaches 100%, the \<Progress> component is hidden, and the web page loading is complete. Add the **onProgressChange** event for the **\<Web>** component, which is triggered when the loading progress changes and returns the progress value in its callback. Assign the progress value to the **\<Progress>** component to control the status of the component. When the progress reaches 100%, the **\<Progress>** component is hidden, and the web page loading is complete.
``` ```
// xxx.ets // xxx.ets
...@@ -89,7 +89,7 @@ struct WebComponent { ...@@ -89,7 +89,7 @@ struct WebComponent {
} }
} }
``` ```
Add the runJavaScript method to the onPageEnd event. The onPageEnd event is triggered when the web page finishes loading. In this case, the runJavaScript method can be used to execute JavaScript scripts in the HTML file. In the sample code below, when the web page finishes loading, the onPageEnd event is triggered to call the test method in the HTML file and print information on the console. Add the **runJavaScript** method to the **onPageEnd** event. The **onPageEnd** event is triggered when the web page finishes loading. In this case, the **runJavaScript** method can be used to execute JavaScript scripts in the HTML file. In the sample code below, when the web page finishes loading, the **onPageEnd** event is triggered to call the **test** method in the HTML file and print information on the console.
``` ```
// xxx.ets // xxx.ets
...@@ -134,7 +134,7 @@ struct WebComponent { ...@@ -134,7 +134,7 @@ struct WebComponent {
} }
``` ```
Create an HTML file in main/resources/rawfile. Create an HTML file in **main/resources/rawfile**.
``` ```
<!-- index.html --> <!-- index.html -->
...@@ -153,31 +153,31 @@ Create an HTML file in main/resources/rawfile. ...@@ -153,31 +153,31 @@ Create an HTML file in main/resources/rawfile.
``` ```
## Scenario Example ## Scenario Example
In this example, you'll implement a \<Web> component where videos can be played dynamically. Embed a video resource into an HTML page, and then use the \<Web> component controller to invoke the onActive and onInactive methods to activate and pause page rendering, respectively. When the page is hidden, the \<Web> component stops rendering and the video playback pauses. When the page is displayed, the \<Web> component is activated and the video playback resumes. In this example, you'll implement a **\<Web>** component where videos can be played dynamically. Embed a video resource into an HTML page, and then use the **\<Web>** component controller to invoke the **onActive** and **onInactive** methods to activate and pause page rendering, respectively. Upon clicking of the **onInactive** button, the **\<Web>** component stops rendering and the video playback pauses. Upon clicking of the **onActive** button, the **\<Web>** component is activated and the video playback resumes.
``` ```
// 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 }) Row() {
.fileAccess(true) Button('onActive').onClick(() => {
console.info("Web Component onActive");
this.controller.onActive();
})
Button('onInactive').onClick(() => {
console.info("Web Component onInactive");
this.controller.onInactive();
})
} }
} Web({ src: $rawfile('index.html'), controller: this.controller })
.fileAccess(true)
onPageHide() {
// Invoked when the page is hidden.
this.controller.onInactive();
}
onPageShow() {
// Invoked when the page is displayed.
this.controller.onActive();
} }
} }
}
``` ```
``` ```
......
...@@ -42,7 +42,7 @@ When you create a system component, the default style is used. You can change th ...@@ -42,7 +42,7 @@ When you create a system component, the default style is used. You can change th
The attribute method must follow the component and be connected by the operator ".". You can also configure multiple attributes of the component in method chaining mode. The attribute method must follow the component and be connected by the operator ".". You can also configure multiple attributes of the component in method chaining mode.
``` ```
@Entry @Entry
@Component @Component
...@@ -62,7 +62,7 @@ When you create a system component, the default style is used. You can change th ...@@ -62,7 +62,7 @@ When you create a system component, the default style is used. You can change th
![en-us_image_0000001267767845](figures/en-us_image_0000001267767845.png) ![en-us_image_0000001267767845](figures/en-us_image_0000001267767845.png)
2. Change the display content of the <Text> component from Hello World to Tomato by modifying the constructor parameters of the <Text> component. 2. Change the display content of the <Text> component from Hello World to Tomato by modifying the constructor parameters of the <Text> component.
``` ```
@Entry @Entry
@Component @Component
......
...@@ -4,28 +4,24 @@ ...@@ -4,28 +4,24 @@
Before creating a project, you need to install DevEco Studio. Before creating a project, you need to install DevEco Studio.
1. Open DevEco Studio and click Create Project. If there is already a project, choose File > New > New project. 1. Open DevEco Studio and click **Create Project**. If there is already a project, choose **File** > **New** > **New project**.
![en-us_image_0000001267607861](figures/en-us_image_0000001267607861.png) ![en-us_image_0000001168956332](figures/en-us_image_0000001168956332.png)
2. 2.
On the page for selecting an ability template, select [Standard]Empty Ability. On the page for selecting an ability template, select **Empty Ability**.
![en-us_image_0000001223127704](figures/en-us_image_0000001223127704.png) ![en-us_image_0000001168059158](figures/en-us_image_0000001168059158.png)
3. 3. On the project configuration page, set **Project name** to **HealthyDiet**, **Project type** to **Application**, **Compile API** to **8**, and **UI Syntax** to **eTS**. By default, DevEco Studio saves the project to drive C. You can change the save path by setting **Save location**. When you are done, click **Finish**.
Install the OpenHarmony SDK.
![en-us_image_0000001223127700](figures/en-us_image_0000001223127700.png)
4. On the project configuration page, set Project Name to HealthyDiet, Project Type to Application, Device Type to Phone, Language to eTS, and Compatible API Version to SDK: API Version 7. By default, DevEco Studio saves the project to drive C. You can change the save path by setting Save Location. When you are done, click Finish. ![en-us_image_0000001167746622](figures/en-us_image_0000001167746622.png)
4. After the project is created, open the **app.ets** file.
![en-us_image_0000001267647849](figures/en-us_image_0000001267647849.png) The **app.ets** file provides the **onCreate** and **onDestroy** methods for the application lifecycle. **onCreate** is called when an application is created, and **onDestroy** is called when an application is destroyed. Global variables can be declared in the **app.ets** file, wherein the declared data and methods are shared by the entire application.
5. After the project is created, open the app.ets file.
The app.ets file provides the onCreate and onDestroy methods for the application lifecycle. onCreate is called when an application is created, and onDestroy is called when an application is destroyed. Global variables can be declared in the app.ets file, wherein the declared data and methods are shared by the entire application.
``` ```
export default { export default {
...@@ -38,7 +34,7 @@ Before creating a project, you need to install DevEco Studio. ...@@ -38,7 +34,7 @@ Before creating a project, you need to install DevEco Studio.
} }
``` ```
6. In the project navigation tree, open index.ets. This page displays the current UI description. The declarative UI framework automatically generates a component-based struct, which complies with the Builder API declaration. The current layout and components are declared in the build method. 5. In the project navigation tree, open **index.ets**. This page displays the current UI description. The declarative UI framework automatically generates a component-based struct, which complies with the Builder API declaration. The current layout and components are declared in the build method.
``` ```
@Entry @Entry
...@@ -56,14 +52,15 @@ Before creating a project, you need to install DevEco Studio. ...@@ -56,14 +52,15 @@ Before creating a project, you need to install DevEco Studio.
} }
``` ```
7. Click Previewer on the right to open the Previewer window. Hello World is displayed in the middle and in bold. 6. Click **Previewer** on the right to open the **Previewer** window. **Hello World** is displayed in the middle and in bold.
If the Previewer button is unavailable, choose Settings > SDK Manager >OpenHarmony SDK > Tools to check whether the Previewer is installed. If the **Previewer** button is unavailable, choose **Settings** > **SDK Manager** > **OpenHarmony SDK** > **Tools** to check whether the Previewer is installed.
![en-us_image_0000001222807756](figures/en-us_image_0000001222807756.png) ![en-us_image_0000001222807756](figures/en-us_image_0000001222807756.png)
8. Install the application and run the application. Connect the device to the computer. After the IDE identifies the device, click Run'entry'. 7. Install the application and run the application. Connect the device to the computer. After the IDE identifies the device, click **Run'entry'**.
![en-us_image_0000001267607865](figures/en-us_image_0000001267607865.png)
![en-us_image_0000001148858818](figures/en-us_image_0000001148858818.png)
Before the installation, you must configure an application signature. For details, see Configuring the OpenHarmony App Signature. After the installation is complete, click the Run icon on the screen to open the application. Hello World is displayed in the center of the screen. Before the installation, you must configure an application signature. For details, see **Configuring the OpenHarmony App Signature**. After the installation is complete, click the **Run** icon on the screen to open the application. **Hello World** is displayed in the center of the screen.
![en-us_image_0000001267647841](figures/en-us_image_0000001267647841.png) ![en-us_image_0000001267647841](figures/en-us_image_0000001267647841.png)
...@@ -46,7 +46,7 @@ In this section, we will develop an infographic food details page, by building c ...@@ -46,7 +46,7 @@ In this section, we will develop an infographic food details page, by building c
![en-us_image_0000001267887861](figures/en-us_image_0000001267887861.png) ![en-us_image_0000001267887861](figures/en-us_image_0000001267887861.png)
3. Access images through resources. 3. Access images through resources.
In addition to specifying the image path, you can also use the media resource symbol $r to reference resources based on the resource qualifier rules in the resources folder. Right-click the resources folder, choose New &gt; Resource Directory, set Resource Type to Media (image resource).Place Tomato.png in the media folder. In addition to specifying the image path, you can also use the media resource symbol $r to reference resources based on the resource qualifier rules in the resources folder. Right-click the resources folder, choose **New** &gt; **Resource Directory**, and set **Resource Type** to **Media (image resource)**. Place Tomato.png in the media folder.
You can then can reference the application resource in the ` "$r('app.type.name')"` format, that is, `$r('app.media.Tomato')`. You can then can reference the application resource in the ` "$r('app.type.name')"` format, that is, `$r('app.media.Tomato')`.
...@@ -70,7 +70,7 @@ In this section, we will develop an infographic food details page, by building c ...@@ -70,7 +70,7 @@ In this section, we will develop an infographic food details page, by building c
4. Set the width and height of the image, and set the objectFit attribute of the image to ImageFit.Contain, which means to keep the aspect ratio of the image to ensure that the image is completely displayed within the boundary.If the image fills the entire screen, the possible causes are as follows: 4. Set the width and height of the image, and set the objectFit attribute of the image to ImageFit.Contain, which means to keep the aspect ratio of the image to ensure that the image is completely displayed within the boundary.If the image fills the entire screen, the possible causes are as follows:
1. The width and height of the image are not set. 1. The width and height of the image are not set.
2. The default attribute of objectFit of the image is ImageFit.Cover, that is, the image is zoomed in or zoomed out to fill the entire display boundary with the aspect ratio locked. 2. The default attribute of **objectFit** of the image is **ImageFit.Cover**, that is, the image is zoomed in or zoomed out to fill the entire display boundary with the aspect ratio locked.
``` ```
@Entry @Entry
...@@ -91,7 +91,7 @@ In this section, we will develop an infographic food details page, by building c ...@@ -91,7 +91,7 @@ In this section, we will develop an infographic food details page, by building c
![en-us_image_0000001223127732](figures/en-us_image_0000001223127732.png) ![en-us_image_0000001223127732](figures/en-us_image_0000001223127732.png)
5. Set the food image and name layout. Set the alignment mode of the stack to bottom alignment. By default, the stack is center aligned. Set alignContent to Alignment.BottomStart. Similar to FontWeight, Alignment is a built-in enumeration type provided by the framework. 5. Set the food image and name layout. Set the alignment mode of the stack to bottom alignment. By default, the stack is center aligned. Set **alignContent** to **Alignment.BottomStart**. Similar to **FontWeight**, **Alignment** is a built-in enumeration type provided by the framework.
``` ```
@Entry @Entry
...@@ -113,8 +113,8 @@ In this section, we will develop an infographic food details page, by building c ...@@ -113,8 +113,8 @@ In this section, we will develop an infographic food details page, by building c
![en-us_image_0000001267647873](figures/en-us_image_0000001267647873.png) ![en-us_image_0000001267647873](figures/en-us_image_0000001267647873.png)
6. You can change the background color of the food image by setting the background color of the stack. You can set the background color in either of the following ways: 6. You can change the background color of the food image by setting the background color of the stack. You can set the background color in either of the following ways:
1. By using the built-in enumeration value of Color provided by the framework. For example, backgroundColor(Color.Red) indicates that the background color is set to red. 1. By using the built-in enumeration value of Color provided by the framework. For example, **backgroundColor(Color.Red)** indicates that the background color is set to red.
2. By using the parameter of the string type. The supported color formats are rgb, rgba, and HEX. For example, you can set the background color to blue by setting backgroundColor(??\#0000FF??) and set the background color to white by setting backgroundColor(??rgb(255, 255, 255)??). 2. By using the parameter of the string type. The supported color formats are rgb, rgba, and HEX. For example, you can set the background color to blue by setting **backgroundColor(??\#0000FF??)** and set the background color to white by setting **backgroundColor(??rgb(255, 255, 255)??)**.
``` ```
...@@ -138,8 +138,8 @@ In this section, we will develop an infographic food details page, by building c ...@@ -138,8 +138,8 @@ In this section, we will develop an infographic food details page, by building c
![en-us_image_0000001222967772](figures/en-us_image_0000001222967772.png) ![en-us_image_0000001222967772](figures/en-us_image_0000001222967772.png)
7. Adjust the left and bottom margin of the &lt;Text&gt; component. Margin is a shorthand attribute. You can specify the margins of the four edges in a unified manner or separately. The configuration method is as follows: 7. Adjust the left and bottom margin of the &lt;Text&gt; component. Margin is a shorthand attribute. You can specify the margins of the four edges in a unified manner or separately. The configuration method is as follows:
1. When the parameter is set to Length, the outer margins of the four edges are specified. For example, margin(20) indicates that the outer margins of the top, right, bottom, and left edges are all 20. 1. When the parameter is set to Length, the outer margins of the four edges are specified. For example, **margin(20)** indicates that the outer margins of the top, right, bottom, and left edges are all 20.
2. {top?: Length, right?: Length, bottom?: Length, left?:Length} specifies the margins of the four edges. For example, margin({ left: 26, bottom: 17.4 }) indicates that the left margin is 26 and the bottom margin is 17.4. 2. **{top?: Length, right?: Length, bottom?: Length, left?:Length}** specifies the margins of the four edges. For example, **margin({ left: 26, bottom: 17.4 })** indicates that the left margin is 26 and the bottom margin is 17.4.
``` ```
...@@ -163,7 +163,7 @@ In this section, we will develop an infographic food details page, by building c ...@@ -163,7 +163,7 @@ In this section, we will develop an infographic food details page, by building c
![en-us_image_0000001222967776](figures/en-us_image_0000001222967776.png) ![en-us_image_0000001222967776](figures/en-us_image_0000001222967776.png)
8. Adjust the structure between components and semanticize component names. Create the FoodDetail page entry component, create a column in FoodDetail, and set the alignment to alignItems(HorizontalAlign.Center). Change the name of the MyComponent component to FoodImageDisplay, which is a child component of the FoodDetail component. 8. Adjust the structure between components and semanticize component names. Create the FoodDetail page entry component, create a column in **FoodDetail**, and set the alignment to **alignItems(HorizontalAlign.Center)**. Change the name of the MyComponent component to FoodImageDisplay, which is a child component of the FoodDetail component.
A column is a container component whose child components are vertically arranged. It is a linear layout in essence. Therefore, only the alignment in the cross axis direction can be set. A column is a container component whose child components are vertically arranged. It is a linear layout in essence. Therefore, only the alignment in the cross axis direction can be set.
...@@ -201,7 +201,7 @@ In this section, we will develop an infographic food details page, by building c ...@@ -201,7 +201,7 @@ In this section, we will develop an infographic food details page, by building c
You can use the Flex layout to build a food composition table. In this way you do not need to worry about the width and height calculation. The size of different cells can be flexibly set based on the proportion. You can use the Flex layout to build a food composition table. In this way you do not need to worry about the width and height calculation. The size of different cells can be flexibly set based on the proportion.
1. Create a ContentTable component as a child component of the FoodDetail component. 1. Create a **ContentTable** component as a child component of the FoodDetail component.
``` ```
@Component @Component
...@@ -279,7 +279,7 @@ You can use the Flex layout to build a food composition table. In this way you d ...@@ -279,7 +279,7 @@ You can use the Flex layout to build a food composition table. In this way you d
![en-us_image_0000001267767869](figures/en-us_image_0000001267767869.png) ![en-us_image_0000001267767869](figures/en-us_image_0000001267767869.png)
3. Adjust the layout and set the proportion (layoutWeight) of each part. Set the proportion of the category name to 1, and the total proportion of content name and content value to 2. The content name and content value are in a same Flex, and the content name occupies all remaining space flexGrow(1). 3. Adjust the layout and set the proportion (layoutWeight) of each part. Set the proportion of the category name to 1, and the total proportion of content name and content value to **2**. The content name and content value are in a same Flex, and the content name occupies all remaining space flexGrow(1).
``` ```
@Component @Component
...@@ -335,8 +335,8 @@ You can use the Flex layout to build a food composition table. In this way you d ...@@ -335,8 +335,8 @@ You can use the Flex layout to build a food composition table. In this way you d
![en-us_image_0000001267607901](figures/en-us_image_0000001267607901.png) ![en-us_image_0000001267607901](figures/en-us_image_0000001267607901.png)
4. Create the Nutrient class in a similar process. Nutrition consists of four parts: Protein, Fat, Carbohydrates, and VitaminC. The names of the last three parts are omitted in the table and represented by spaces. 4. Create the **Nutrient** class in a similar process. Nutrition consists of four parts: Protein, Fat, Carbohydrates, and VitaminC. The names of the last three parts are omitted in the table and represented by spaces.
Set FlexDirection.Column, FlexAlign.SpaceBetween, and ItemAlign.Start. Set **FlexDirection.Column**, **FlexAlign.SpaceBetween**, and **ItemAlign.Start**.
``` ```
......
# Flex Layout
The **\<Flex>** component is used to create a flex layout. In a flex container created using the **Flex** API, child components can be laid out flexibly. For example, if there are three child components in a flex container, they can be horizontally centered and vertically equally spaced.
## Creating a Flex Layout
The available API is as follows:
Flex(options?: { direction?: FlexDirection, wrap?: FlexWrap, justifyContent?: FlexAlign, alignItems?: ItemAlign, alignContent?: FlexAlign })
The **direction** parameter defines the flex layout direction. The **justifyContent** parameter defines the alignment mode of child components in the flex layout direction. The **alignContent** parameter defines the alignment mode of child components in the vertical direction. The **wrap** parameter defines whether the content can wrap onto multiple lines.
## Flex Layout Direction
The flex layout has two directions, following two axes. The main axis is the axis along which the child components follow each other. The cross axis is the axis perpendicular to the main axis. The **direction** parameter establishes the main axis. The available options are as follows:
- **FlexDirection.Row** (default value): The main axis runs along the row horizontally, and the child components start from the start edge of the main axis.
```
Flex({ direction: FlexDirection.Row }) {
Text('1').width('33%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('33%').height(50).backgroundColor(0xD2B48C)
Text('3').width('33%').height(50).backgroundColor(0xF5DEB3)
}
.height(70)
.width('90%')
.padding(10)
.backgroundColor(0xAFEEEE)
```
![en-us_image_0000001218579606](figures/en-us_image_0000001218579606.png)
- **FlexDirection.RowReverse**: The main axis runs along the row horizontally, and the child components start from the end edge of the main axis, in a direction opposite to **FlexDirection.Row**.
```
Flex({ direction: FlexDirection.RowReverse }) {
Text('1').width('33%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('33%').height(50).backgroundColor(0xD2B48C)
Text('3').width('33%').height(50).backgroundColor(0xF5DEB3)
}
.height(70)
.width('90%')
.padding(10)
.backgroundColor(0xAFEEEE)
```
![en-us_image_0000001218739566](figures/en-us_image_0000001218739566.png)
- **FlexDirection.Column**: The main axis runs along the column vertically, and the child components start from the start edge of the main axis.
```
Flex({ direction: FlexDirection.Column }) {
Text('1').width('100%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('100%').height(50).backgroundColor(0xD2B48C)
Text('3').width('100%').height(50).backgroundColor(0xF5DEB3)
}
.height(70)
.width('90%')
.padding(10)
.backgroundColor(0xAFEEEE)
```
![en-us_image_0000001263019457](figures/en-us_image_0000001263019457.png)
- **FlexDirection.ColumnReverse**: The main axis runs along the column vertically, and the child components start from the end edge of the main axis, in a direction opposite to **FlexDirection.Column**.
```
Flex({ direction: FlexDirection.ColumnReverse }) {
Text('1').width('100%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('100%').height(50).backgroundColor(0xD2B48C)
Text('3').width('100%').height(50).backgroundColor(0xF5DEB3)
}
.height(70)
.width('90%')
.padding(10)
.backgroundColor(0xAFEEEE)
```
![en-us_image_0000001263339459](figures/en-us_image_0000001263339459.png)
## Wrapping in the Flex Layout
By default, child components are laid out on a single line (also called an axis) in the flex container. Use the **wrap** parameter to set whether child components can wrap onto multiple lines. The available options are as follows:
- **FlexWrap.NoWrap**: Child components are laid out on a single line. This may cause the child components to shrink to fit the container when the total width of the child components is greater than the width of the container.
```
Flex({ wrap: FlexWrap.NoWrap }) {
Text('1').width('50%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('50%').height(50).backgroundColor(0xD2B48C)
Text('3').width('50%').height(50).backgroundColor(0xF5DEB3)
}
.width('90%')
.padding(10)
.backgroundColor(0xAFEEEE)
```
![en-us_image_0000001263139409](figures/en-us_image_0000001263139409.png)
- **FlexWrap.Wrap**: Child components can break into multiple lines.
```
Flex({ wrap: FlexWrap.Wrap }) {
Text('1').width('50%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('50%').height(50).backgroundColor(0xD2B48C)
Text('3').width('50%').height(50).backgroundColor(0xD2B48C)
}
.width('90%')
.padding(10)
.backgroundColor(0xAFEEEE)
```
![en-us_image_0000001218419614](figures/en-us_image_0000001218419614.png)
- **FlexWrap.WrapReverse**: Child components can break into multiple lines in the reverse order to the row.
```
Flex({ wrap: FlexWrap.WrapReverse}) {
Text('1').width('50%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('50%').height(50).backgroundColor(0xD2B48C)
Text('3').width('50%').height(50).backgroundColor(0xF5DEB3)
}
.width('90%')
.padding(10)
.backgroundColor(0xAFEEEE)
```
![en-us_image_0000001263259399](figures/en-us_image_0000001263259399.png)
## Alignment in the Flex Layout
### Alignment on the Main Axis
Use the **justifyContent** parameter to set alignment of items on the main axis. The available options are as follows:
- **FlexAlign.Start**: The items are aligned with each other toward the start edge of the container along the main axis.
```
Flex({ justifyContent: FlexAlign.Start }) {
Text('1').width('20%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('20%').height(50).backgroundColor(0xD2B48C)
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
}
.width('90%')
.padding(10)
.backgroundColor(0xAFEEEE)
```
![en-us_image_0000001218259634](figures/en-us_image_0000001218259634.png)
- **FlexAlign.Center**: The items are aligned with each other toward the center of the container along the main axis. The space between the first component and the main-start is the same as that between the last component and the main-end.
```
Flex({ justifyContent: FlexAlign.Center }) {
Text('1').width('20%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('20%').height(50).backgroundColor(0xD2B48C)
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
}
.width('90%')
.padding(10)
.backgroundColor(0xAFEEEE)
```
![en-us_image_0000001218579608](figures/en-us_image_0000001218579608.png)
- **FlexAlign.End**: The items are aligned with each other toward the end edge of the container along the main axis.
```
Flex({ justifyContent: FlexAlign.End }) {
Text('1').width('20%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('20%').height(50).backgroundColor(0xD2B48C)
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
}
.width('90%')
.padding(10)
.backgroundColor(0xAFEEEE)
```
![en-us_image_0000001218739568](figures/en-us_image_0000001218739568.png)
- **FlexAlign.SpaceBetween**: The items are evenly distributed within the container along the main axis. The first item is aligned with the main-start, the last item is aligned with the main-end, and the remaining items are distributed so that the space between any two adjacent items is the same.
```
Flex({ justifyContent: FlexAlign.SpaceBetween }) {
Text('1').width('20%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('20%').height(50).backgroundColor(0xD2B48C)
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
}
.width('90%')
.padding(10)
.backgroundColor(0xAFEEEE)
```
![en-us_image_0000001263019461](figures/en-us_image_0000001263019461.png)
- **FlexAlign.SpaceAround**: The items are evenly distributed within the container along the main axis. The space between the first item and main-start, and that between the last item and cross-main are both half the size of the space between two adjacent items.
```
Flex({ justifyContent: FlexAlign.SpaceAround }) {
Text('1').width('20%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('20%').height(50).backgroundColor(0xD2B48C)
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
}
.width('90%')
.padding(10)
.backgroundColor(0xAFEEEE)
```
![en-us_image_0000001263339461](figures/en-us_image_0000001263339461.png)
- **FlexAlign.SpaceEvenly**: The items are equally distributed along the main axis. The space between the first item and main-start, the space between the last item and main-end, and the space between two adjacent items are the same.
```
Flex({ justifyContent: FlexAlign.SpaceEvenly }) {
Text('1').width('20%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('20%').height(50).backgroundColor(0xD2B48C)
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
}
.width('90%')
.padding(10)
.backgroundColor(0xAFEEEE)
```
![en-us_image_0000001263139411](figures/en-us_image_0000001263139411.png)
### Alignment on the Cross Axis
Use the **alignItems** parameter to set alignment of items on the cross axis. The available options are as follows:
- **ItemAlign.Auto**: The items are automatically aligned in the flex container.
```
Flex({ alignItems: ItemAlign.Auto }) {
Text('1').width('33%').height(30).backgroundColor(0xF5DEB3)
Text('2').width('33%').height(40).backgroundColor(0xD2B48C)
Text('3').width('33%').height(50).backgroundColor(0xF5DEB3)
}
.size({width: '90%', height: 80})
.padding(10)
.backgroundColor(0xAFEEEE)
```
![en-us_image_0000001218419616](figures/en-us_image_0000001218419616.png)
- **ItemAlign.Start**: The items are aligned with the start edge of the container along the cross axis.
```
Flex({ alignItems: ItemAlign.Start }) {
Text('1').width('33%').height(30).backgroundColor(0xF5DEB3)
Text('2').width('33%').height(40).backgroundColor(0xD2B48C)
Text('3').width('33%').height(50).backgroundColor(0xF5DEB3)
}
.size({width: '90%', height: 80})
.padding(10)
.backgroundColor(0xAFEEEE)
```
![en-us_image_0000001263259401](figures/en-us_image_0000001263259401.png)
- **ItemAlign.Start**: The items are aligned with the center of the container along the cross axis.
```
Flex({ alignItems: ItemAlign.Center }) {
Text('1').width('33%').height(30).backgroundColor(0xF5DEB3)
Text('2').width('33%').height(40).backgroundColor(0xD2B48C)
Text('3').width('33%').height(50).backgroundColor(0xF5DEB3)
}
.size({width: '90%', height: 80})
.padding(10)
.backgroundColor(0xAFEEEE)
```
![en-us_image_0000001218259636](figures/en-us_image_0000001218259636.png)
- **ItemAlign.End**: The items are aligned with the end edge of the container along the cross axis.
```
Flex({ alignItems: ItemAlign.End }) {
Text('1').width('33%').height(30).backgroundColor(0xF5DEB3)
Text('2').width('33%').height(40).backgroundColor(0xD2B48C)
Text('3').width('33%').height(50).backgroundColor(0xF5DEB3)
}
.size({width: '90%', height: 80})
.padding(10)
.backgroundColor(0xAFEEEE)
```
![en-us_image_0000001218579610](figures/en-us_image_0000001218579610.png)
- **ItemAlign.Stretch**: The items are stretched along the cross axis. If no constraints are set, the items are stretched to fill the size of the container on the cross axis.
```
Flex({ alignItems: ItemAlign.Stretch }) {
Text('1').width('33%').height(30).backgroundColor(0xF5DEB3)
Text('2').width('33%').height(40).backgroundColor(0xD2B48C)
Text('3').width('33%').height(50).backgroundColor(0xF5DEB3)
}
.size({width: '90%', height: 80})
.padding(10)
.backgroundColor(0xAFEEEE)
```
![en-us_image_0000001218739570](figures/en-us_image_0000001218739570.png)
- **ItemAlign.Baseline**: The items are aligned at the baseline of the cross axis.
```
Flex({ alignItems: ItemAlign.Baseline }) {
Text('1').width('33%').height(30).backgroundColor(0xF5DEB3)
Text('2').width('33%').height(40).backgroundColor(0xD2B48C)
Text('3').width('33%').height(50).backgroundColor(0xF5DEB3)
}
.size({width: '90%', height: 80})
.padding(10)
.backgroundColor(0xAFEEEE)
```
![en-us_image_0000001263019463](figures/en-us_image_0000001263019463.png)
### Content Alignment
Use the **alignContent** parameter to set how content items are aligned within the flex container along the cross axis.
- **FlexAlign.Start**: The items are packed to the start of the container.
- **FlexAlign.Center**: The items are packed to the center of the container.
- **FlexAlign.End**: The items are packed to the end of the container.
- **FlexAlign.SpaceBetween**: The items are evenly distributed; the first item is aligned with the main-start while the last one is aligned with the main-end.
- **FlexAlign.SpaceAround**: The items are evenly distributed, with the space between the item and the main-start and between the item and the main-end equals half of the space between adjacent items.
- **FlexAlign.SpaceEvenly**: The items are evenly distributed, with the space between the item and the main-start and between the item and the main-end equals the space between adjacent items.
## Example Scenario
In this example, a flex layout is designed to achieve the following effects: The child components are laid out horizontally on a single line, even when the total width of the child components exceeds the width of the container; the child components are horizontally aligned at both ends and vertically aligned toward the center of the container; the space is evenly divided by the child components except for the start and end ones.
```
@Entry
@Component
struct FlexExample {
build() {
Column() {
Column({ space: 5 }) {
Flex({ direction: FlexDirection.Row, wrap: FlexWrap.NoWrap, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) {
Text('1').width('30%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('30%').height(50).backgroundColor(0xD2B48C)
Text('3').width('30%').height(50).backgroundColor(0xF5DEB3)
}
.height(70)
.width('90%')
.padding(10)
.backgroundColor(0xAFEEEE)
}.width('100%').margin({ top: 5 })
}.width('100%')
}
}
```
![en-us_image_0000001261605867](figures/en-us_image_0000001261605867.png)
# Grid Layout
As a tool to provide layout auxiliary lines, the grid system is handy in graphic and website design. When employed in the UI design of mobile devices, the grid system exhibits the following advantages:
1. Provides rules for layout design and resolves issues of dynamic layout across devices with different sizes.
2. Provides a unified positioning method for the system to ensure layout consistency among modules on different devices.
3. Provides a flexible spacing adjustment method for applications to keep up with layout in special scenarios.
To implement the grid layout, the declarative paradigm provides the \<GridContainer> component, together with the universal attribute useSizeType of its child components.
## Grid System
The grid system works in terms of columns, margins, and gutters.
![en-us_image_0000001217236574](figures/en-us_image_0000001217236574.png)
1. Gutters:
Spacing between elements. You can define different clutter values for different device sizes as part of the overall grid layout specifications. For better results, make sure the gutter is not greater than the margin.
2. Margins:
Spacing around an item in the grid container. You can define different margin values for different device sizes as part of the overall grid layout specifications.
3. Columns:
Main tool for positioning items in the grid layout. The grid container is divided into different columns based on the device size. The width of each column is calculated based on the total number of columns while respecting the margin and clutter specifications.
### Grid Breakpoints
Breakpoints in the grid system are set in terms of the device's screen pixel density. The grid system defines a set of breakpoint rules based on the mapping between the numbers of columns and device screen widths.
Depending on the screen width, devices are classified into different width types. The table below provides the mappings of the grid breakpoint ranges, device width types, default total number of columns, margins, and gutters.
<a id="grid_system_define">Grid layout</a>
| Grid Breakpoint Range| Device Width Type| Description| Columns| Gutter| Margin|
| -------- | -------- | -------- | -------- | -------- | -------- |
| 0 &lt; Device screen width &lt; 320 vp | XS | Device of the minimum size.| 2 | 12 vp| 12 vp|
| 320 vp &lt;= Device screen width &lt; 600 vp| SM | Small-sized device.| 4 | 24 vp| 24 vp|
| 600 vp lt;= Device screen width lt;840 vp| MD | Medium-sized device.| 8 | 24 vp| 32 vp|
| 840 vp &lt;= Device screen width| LG | Large-sized device.| 12 | 24 vp| 48 vp|
## Usage
Create a grid container, define the grid layout, and set the number of columns for child components in the grid container under different device width types.
### Creating a Grid Container
Use the **GridContainer(options?: { columns?: number | 'auto', sizeType?: SizeType, gutter?: Length, margin?: Length})** API to create a grid container. All child components in the grid container follow the grid layout.
Use the **columns**, **gutter**, and **margin** parameters to define your grid layout. In the sample below, the grid container is divided into six columns, with the gutter (spacing between columns) of 10 vp and the margin (spacing around a column) of 20 vp.
```
GridContainer({ columns: 6, gutter: 10, margin: 20 }) {}
```
In the sample below, the grid container does not have any parameter set. In this case, it follows the default layout, as in the case when sizeType is set to SizeType.Auto.
```
GridContainer() {}
```
On a small-sized device (**SizeType.SM**), the grid container is divided into four columns by default, with the gutter of 24 vp and the margin of 24 vp. On a medium-sized device (**SizeType.MD**), the grid container is divided into eight columns by default, with the gutter of 24 vp and the margin of 32 vp.
You can also use **sizeType** to configure child components in the grid container to follow the grid settings for a specific device width type, as shown below:
```
GridContainer({ sizeType: SizeType.SM) {
Row() {
Text('1')
.useSizeType({
xs: { span: 2},
sm: { span: 3, offset: 1 },
md: { span: 6, offset: 2 },
lg: { span: 8, offset: 2 },
})
}
}
```
In the preceding example, the **\<Text>** component uses the grid setting of the **SizeType.SM** type regardless of the actual width type of the device. That is, the **\<Text>** component occupies three columns and is placed in the first column.
### Grid Settings of Child Components in the Grid Container
Use the universal attribute **useSizeType** to configure the positioning of child components in the grid container. span indicates the number of columns occupied by the child component. offset indicates the column offset, that is, the column where the component is located. The sample code is as follows:
```
GridContainer() {
Row() {
Text('1')
.useSizeType({
xs: { span: 2},
sm: { span: 3, offset: 1 },
md: { span: 6, offset: 2 },
lg: { span: 8, offset: 2 },
})
}
}
```
In the preceding example, **sm: { span: 2, offset: 0 }** indicates that on a medium-sized device, the **\<Text>** component occupies three columns and is placed in the first column of the grid container.
## Example Scenario
The grid layout helps ensure proper display of components among different device width types, eliminating the hassle of writing a large amount of code for device compatibility.
```
@Entry
@Component
struct GridContainerExample {
build() {
Column({ space: 5 }) {
GridContainer({ columns: 6, sizeType: SizeType.Auto, gutter: 10, margin: 20 }) {
Row() {
Text('1')
.useSizeType({
xs: { span: 2, offset: 0 },
sm: { span: 2, offset: 0 },
md: { span: 1, offset: 0 },
lg: { span: 1, offset: 0 },
})
.height(100).backgroundColor(0x4682B4).textAlign(TextAlign.Center)
Text('2')
.useSizeType({
xs: { span: 2, offset: 2 },
sm: { span: 2, offset: 2 },
md: { span: 4, offset: 1 },
lg: { span: 4, offset: 1 },
})
.height(100).backgroundColor(0x46F2B4).textAlign(TextAlign.Center)
Text('3')
.useSizeType({
xs: { span: 2, offset: 4 },
sm: { span: 2, offset: 4 },
md: { span: 1, offset: 5 },
lg: { span: 1, offset: 5 },
})
.height(100).backgroundColor(0x46A2B4).textAlign(TextAlign.Center)
}
}.width('80%').backgroundColor('gray')
}.width('100%').margin({ top: 15 })
}
}
```
Effect on a small-sized device (**SizeType.SM**):
![en-us_image_0000001218108718](figures/en-us_image_0000001218108718.png)
Effect on a medium-sized device (**SizeType.MD**):
![en-us_image_0000001262748569](figures/en-us_image_0000001262748569.png)
# Media Query
Media queries are widely used on mobile devices. You can use them to modify the application style based on the device type or specific features and device parameters (such as the screen resolution). Specifically, media queries allow you to:
1. Design a layout style based on the device and app attributes.
2. Update the page layout to adapt to dynamic screen changes (for example, screen splitting or switching between landscape and portrait modes).
## Usage
Invoke the **mediaquery** API to set the media query condition and the callback, and change the page layout or implement service logic in the callback corresponding to the condition.
First, import the mediaquery module, as shown below:
```
import mediaquery from '@ohos.mediaquery'
```
Then, use the **matchMediaSync** API to set the media query condition and save the returned listener, as shown below:
```
listener = mediaquery.matchMediaSync('(orientation: landscape)')
```
Finally, register the callback using the saved listener, and change the page layout or implement service logic in the callback. When the media query condition is matched, the callback is triggered. The sample code is as follows:
```
onPortrait(mediaQueryResult) {
if (mediaQueryResult.matches) {
// do something here
} else {
// do something here
}
}
listener.on('change', onPortrait)
```
## Syntax of Media Query Conditions
```
[media-type] [and|not|only] [(media-feature)]
```
Examples are as follows:
screen and (round-screen: true) // This condition is met when the device screen is round.
(max-height: 800) // The condition is met when the height is less than 800.
(height &lt;= 800) // The condition is met when the height is less than 800.
screen and (device-type: tv) or (resolution &lt; 2) // This is a multi-condition complex statement query containing multiple media features.
### media-type
| Type| Description|
| -------- | -------- |
| screen | Media query based on screen-related parameters.|
### Media Logic Operation (and|not|only)
You can use logical operators (**and**, **or**, **not**, and **only**) to compose complex media queries. You can also combine them using comma (,). The following table describes the operators.
**Table 1** Media logical operators
| Type| Description|
| -------- | -------- |
| and | The **and** operator is used to combine multiple media features into one media query, in a logical AND operation. The query is valid only when all media features are true. It can also combine media types and media functions.<br>For example, **screen&nbsp;and&nbsp;(device-type:&nbsp;wearable)&nbsp;and&nbsp;(max-height:&nbsp;600)&nbsp;** indicates that the query is valid when the device type is wearable and the maximum height of the application is 600 pixel units.|
| not | The **not** operator is used to perform a logical negation for a media query. **true** is returned if the query condition is not met. Otherwise, **false** is returned. In a media query list, logical negation is performed only for the media query using the **not** operator.<br>For example, **not&nbsp;screen&nbsp;and&nbsp;(min-height:&nbsp;50)&nbsp;and&nbsp;(max-height:&nbsp;600)&nbsp;** indicates that the query is valid when the height of the application is less than 50 pixel units or greater than 600 pixel units.<br>>&nbsp;![icon-note.gif](public_sys-resources/icon-note.gif)&nbsp;**NOTE**<br>>&nbsp;When the **not** operator is used, the media type must be specified.|
| only | The **only** operator applies the selected style only when the entire expression is matched. It can be used to prevent ambiguity on browsers of earlier versions. The statements that contain both media types and media features produce ambiguity when they are received by some browsers of earlier versions. For example:<br>screen&nbsp;and&nbsp;(min-height:&nbsp;50)<br>The browsers of earlier versions would mislead this sentence into screen, causing the fact that the specified style is applied when only the media type is matched. In this case, the **only** operator can be used to avoid this problem.<br>>&nbsp;![icon-note.gif](public_sys-resources/icon-note.gif)&nbsp;**NOTE**<br>>&nbsp;When the **only** operator is used, the media type must be specified.|
| ,(comma) | The **or** operator is used to combine multiple media features into one media query, in a logical OR operation. The query is valid if a media feature is true. The effect of a comma operator is equivalent to that of the **or** operator.<br>For example, **screen&nbsp;and&nbsp;(min-height:&nbsp;1000),&nbsp;&nbsp;(round-screen: true)&nbsp;** indicates that the query is valid when the minimum height of the application is 1000 pixel units or the device screen is round.|
| or | The **or** operator is used to combine multiple media features into one media query, in a logical OR operation. The query is valid if a media feature is true.<br>For example, **screen&nbsp;and&nbsp;(max-height:&nbsp;1000)&nbsp;or&nbsp;&nbsp;(round-screen: true)** indicates that the query is valid when the maximum height of the application is 1000 pixel units or the device screen is round.|
At MediaQuery Level 4, range query is imported so that you can use the operators including &lt;=, &gt;=, &lt;, and &gt; besides the **max-** and **min-** operators.
**Table 2** Logical operators for range query
| Type| Description|
| -------- | -------- |
| &lt;= | Less than or equal to, for example, **screen&nbsp;and&nbsp;(50&nbsp;&lt;=&nbsp;height)**.|
| &gt;= | Greater than or equal to, for example, **screen&nbsp;and&nbsp;(600&nbsp;&gt;=&nbsp;height)**.|
| &lt; | Less than, for example, **screen&nbsp;and&nbsp;(50&nbsp;&lt;&nbsp;height)**.|
| &gt; | Greater than, for example, **screen&nbsp;and&nbsp;(600&nbsp;&gt;&nbsp;height)**.|
### media-feature
| Type| Description|
| -------- | -------- |
| height | Height of the display area on the application page.|
| min-height | Minimum height of the display area on the application page.|
| max-height | Maximum height of the display area on the application page.|
| width | Width of the display area on the app page.|
| min-width | Minimum width of the display area on the application page.|
| max-width | Maximum width of the display area on the application page.|
| resolution | Resolution of the device. The unit can be dpi, dppx, or dpcm.<br>-&nbsp;**dpi** indicates the number of physical pixels per inch. 1 dpi ≈ 0.39 dpcm.<br>-&nbsp;**dpcm** indicates the number of physical pixels per centimeter. 1 dpcm&nbsp;&nbsp;2.54 dpi.<br>-&nbsp;**dppx** indicates the number of physical pixels in each pixel. (This unit is calculated based on this formula: 96 px = 1 inch, which is different from the calculation method of the px unit on the page.) 1 dppx&nbsp;=&nbsp;96 dpi.|
| min-resolution | Minimum device resolution.|
| max-resolution | Maximum device resolution.|
| orientation | Screen orientation.<br>Options are as follows:<br>-&nbsp;orientation:&nbsp;portrait<br>-&nbsp;orientation:&nbsp;landscape|
| device-height | Height of the device.|
| min-device-height | Minimum height of the device.|
| max-device-height | Maximum height of the device.|
| device-width | Width of the device.|
| min-device-width | Minimum width of the device.|
| max-device-width | Maximum width of the device.|
| round-screen | Screen type. The value **true** means that the screen is round, and **false** means the opposite.|
| dark-mode | Whether the device is in dark mode. The value **true** means that the device is in dark mode, and **false** means the opposite.|
## Example Scenario
Use media queries to apply different content and styles to the page text when the screen is switched between landscape and portrait modes.
```
import mediaquery from '@ohos.mediaquery'
let portraitFunc = null
@Entry
@Component
struct MediaQueryExample {
@State color: string = '#DB7093'
@State text: string = 'Portrait'
@State fontSize: number = 24
listener = mediaquery.matchMediaSync('(orientation: landscape)')
onPortrait(mediaQueryResult) {
if (mediaQueryResult.matches) {
this.color = '#FFD700'
this.text = 'Landscape'
} else {
this.color = '#DB7093'
this.text = 'Portrait'
}
}
aboutToAppear() {
portraitFunc = this.onPortrait.bind(this) //bind current js instance
this.listener.on('change', portraitFunc)
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text(this.text).fontSize(50).fontColor(this.color)
}
.width('100%').height('100%')
}
}
```
When the device is in landscape orientation, the text content is displayed in landscape mode in the color of #FFD700.<br/>
![zh-cn_image_0000001262954829](figures/zh-cn_image_0000001262954829.png)
When the device is not in landscape orientation, the text content is displayed in portrait mode in the color of #DB7093.<br/>
![en-us_image_0000001263074739](figures/en-us_image_0000001263074739.png)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册