• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# canvas组件
2<!--Kit: ArkUI-->
3<!--Subsystem: ArkUI-->
4<!--Owner: @sd-wu-->
5<!--Designer: @sunbees-->
6<!--Tester: @liuli0427-->
7<!--Adviser: @HelloCrease-->
8
9>  **说明:**
10>  从API version 4开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
11
12提供画布组件。用于自定义绘制图形。
13
14## 权限列表
15
1617
18
19## 子组件
20
21不支持。
22
23
24## 属性
25
26支持[通用属性](js-components-common-attributes.md)。
27
28
29## 样式
30
31支持[通用样式](js-components-common-styles.md)。
32
33
34## 事件
35
36支持[通用事件](js-components-common-events.md)。
37
38
39## 方法
40
41除支持[通用方法](js-components-common-methods.md)外,还支持如下方法:
42
43
44### getContext
45
46getContext(type: '2d', options?:  ContextAttrOptions): CanvasRenderingContext2D
47
48获取canvas绘图上下文。不支持在onInit和onReady中进行调用。
49
50**参数:**
51
52| 参数名                  | 参数类型               | 必填   | 描述                                       |
53| -------------------- | ------------------ | ---- | ---------------------------------------- |
54| type                 | string             | 是    | 设置为'2d',返回值为2D绘制对象,该对象可用于在画布组件上绘制矩形、文本、图片等。 |
55| options<sup>6+</sup> | ContextAttrOptions | 否    | 当前仅支持配置是否开启抗锯齿功能,默认为关闭。                  |
56
57  **表1** ContextAttrOptions
58
59| 参数名       | 类型      | 说明                  |
60| --------- | ------- | ------------------- |
61| antialias | boolean | 是否开启抗锯齿功能,默认为false,表示不开启抗锯齿功能。 |
62
63**返回值:**
64
65| 类型                                       | 说明                   |
66| ---------------------------------------- | -------------------- |
67| [CanvasRenderingContext2D](js-components-canvas-canvasrenderingcontext2d.md) | 用于在画布组件上绘制矩形、文本、图片等。 |
68
69### toDataURL<sup>6+</sup>
70
71toDataURL(type?: string, quality?: number): string
72
73生成一个包含图片展示的URL。
74
75**参数:**
76
77| 参数名     | 参数类型   | 必填   | 描述                                       |
78| ------- | ------ | ---- | ---------------------------------------- |
79| type    | string | 否    | 可选参数,用于指定图像格式,默认格式为image/png。            |
80| quality | number | 否    | 在指定图片格式为image/jpegimage/webp的情况下,可以从0到1的区间内选择图片的质量。如果超出取值范围,将会使用默认值0.92。 |
81
82**返回值:**
83
84| 类型     | 说明        |
85| ------ | --------- |
86| string | 图像的URL地址。 |
87
88## 示例
89
90```html
91<!-- xxx.hml -->
92<div>
93  <canvas ref="canvas1" style="width: 200px; height: 150px; background-color: #ffff00;"></canvas>
94  <input type="button" style="width: 180px; height: 60px;" value="fillStyle" onclick="handleClick" />
95</div>
96```
97
98```js
99// xxx.js
100export default {
101  handleClick() {
102    const el = this.$refs.canvas1;
103    var dataURL = el.toDataURL();
104    console.log(dataURL);
105    // "data:image/png;base64,xxxxxxxx..."
106  }
107}
108```
109