• 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
10Canvas提供画布组件,用于自定义绘制图形,开发者使用CanvasRenderingContext2D对象和OffscreenCanvasRenderingContext2D对象在Canvas组件上进行绘制,绘制对象可以是基础形状、文本、图片等。
11
12
13## 使用画布组件绘制自定义图形
14
15可以由以下三种形式在画布绘制自定义图形:
16
17
18- 使用[CanvasRenderingContext2D](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md)对象在Canvas画布上绘制。
19
20  ```ts
21  @Entry
22  @Component
23  struct CanvasExample1 {
24    //用来配置CanvasRenderingContext2D对象的参数,包括是否开启抗锯齿,true表明开启抗锯齿。
25    private settings: RenderingContextSettings = new RenderingContextSettings(true);
26    //用来创建CanvasRenderingContext2D对象,通过在canvas中调用CanvasRenderingContext2D对象来绘制。
27    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
28
29    build() {
30      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
31        //在canvas中调用CanvasRenderingContext2D对象。
32        Canvas(this.context)
33          .width('100%')
34          .height('100%')
35          .backgroundColor('#F5DC62')
36          .onReady(() => {
37            //可以在这里绘制内容。
38            this.context.strokeRect(50, 50, 200, 150);
39          })
40      }
41      .width('100%')
42      .height('100%')
43    }
44  }
45  ```
46
47  ![2023022793003](figures/2023022793003.jpg)
48
49- 离屏绘制是指将需要绘制的内容先绘制在缓存区,再将其转换成图片,一次性绘制到Canvas上,加快了绘制速度。过程为:
50  1. 通过transferToImageBitmap方法将离屏画布最近渲染的图像创建为一个ImageBitmap对象。
51  2. 通过CanvasRenderingContext2D对象的transferFromImageBitmap方法显示给定的ImageBitmap对象。
52
53    具体使用参考[OffscreenCanvasRenderingContext2D](../reference/apis-arkui/arkui-ts/ts-offscreencanvasrenderingcontext2d.md)对象。
54
55  ```ts
56  @Entry
57  @Component
58  struct CanvasExample2 {
59    //用来配置CanvasRenderingContext2D对象和OffscreenCanvasRenderingContext2D对象的参数,包括是否开启抗锯齿。true表明开启抗锯齿
60    private settings: RenderingContextSettings = new RenderingContextSettings(true);
61    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
62    //用来创建OffscreenCanvas对象,width为离屏画布的宽度,height为离屏画布的高度。通过在canvas中调用OffscreenCanvasRenderingContext2D对象来绘制。
63    private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600);
64
65    build() {
66      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
67        Canvas(this.context)
68          .width('100%')
69          .height('100%')
70          .backgroundColor('#F5DC62')
71          .onReady(() => {
72            let offContext = this.offCanvas.getContext("2d", this.settings)
73            //可以在这里绘制内容
74            offContext.strokeRect(50, 50, 200, 150);
75            //将离屏绘制渲染的图像在普通画布上显示
76            let image = this.offCanvas.transferToImageBitmap();
77            this.context.transferFromImageBitmap(image);
78          })
79      }
80      .width('100%')
81      .height('100%')
82    }
83  }
84  ```
85
86  ![2023022793003(1)](figures/2023022793003.jpg)
87
88  >**说明:**
89  >
90  >在画布组件中,通过CanvasRenderingContext2D对象和OffscreenCanvasRenderingContext2D对象在Canvas组件上进行绘制时调用的接口相同,另外,接口参数如无特别说明,单位均为vp。
91
92- 在Canvas上加载Lottie动画时,需要先按照如下方式下载Lottie。
93
94  ```ts
95  import lottie from '@ohos/lottie';
96  ```
97
98  具体接口请参考[lottie](https://gitcode.com/openharmony-tpc/lottieArkTS)99
100
101## 初始化画布组件
102
103onReady(event: () =&gt; void)是Canvas组件初始化完成时的事件回调,调用该事件后,可获取Canvas组件的确定宽高,进一步使用CanvasRenderingContext2D对象和OffscreenCanvasRenderingContext2D对象调用相关API进行图形绘制。
104
105```ts
106Canvas(this.context)
107  .width('100%')
108  .height('100%')
109  .backgroundColor('#F5DC62')
110  .onReady(() => {
111    this.context.fillStyle = '#0097D4';
112    this.context.fillRect(50, 50, 100, 100);
113  })
114```
115
116![2023022793350(1)](figures/2023022793350.jpg)
117
118
119## 画布组件绘制方式
120
121在Canvas组件生命周期接口onReady()调用之后,开发者可以直接使用canvas组件进行绘制。或者可以脱离Canvas组件和onReady()生命周期,单独定义Path2d对象构造理想的路径,并在onReady()调用之后使用Canvas组件进行绘制。
122
123- 通过CanvasRenderingContext2D对象和OffscreenCanvasRenderingContext2D对象直接调用相关API进行绘制。
124
125  ```ts
126  Canvas(this.context)
127    .width('100%')
128    .height('100%')
129    .backgroundColor('#F5DC62')
130    .onReady(() => {
131      this.context.beginPath();
132      this.context.moveTo(50, 50);
133      this.context.lineTo(280, 160);
134      this.context.stroke();
135     })
136  ```
137
138  ![2023022793719(1)](figures/2023022793719.jpg)
139
140- 先单独定义path2d对象构造理想的路径,再通过调用CanvasRenderingContext2D对象和OffscreenCanvasRenderingContext2D对象的stroke接口或者fill接口进行绘制,具体使用可以参考[Path2D](../reference/apis-arkui/arkui-ts/ts-components-canvas-path2d.md)对象。
141
142  ```ts
143  Canvas(this.context)
144    .width('100%')
145    .height('100%')
146    .backgroundColor('#F5DC62')
147    .onReady(() => {
148       let region = new Path2D();
149       region.arc(100, 75, 50, 0, 6.28);
150       this.context.stroke(region);
151    })
152  ```
153
154  ![2023022794031(1)](figures/2023022794031.jpg)
155
156
157## 画布组件常用方法
158
159OffscreenCanvasRenderingContext2D对象和CanvasRenderingContext2D对象提供了大量的属性和方法,可以用来绘制文本、图形,处理像素等,是Canvas组件的核心。常用接口有[fill](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#fill)(对封闭路径进行填充)、[clip](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#clip)(设置当前路径为剪切路径)、[stroke](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#stroke)(进行边框绘制操作)等等,同时提供了[fillStyle](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#fillstyle)(指定绘制的填充色)、[globalAlpha](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#globalalpha)(设置透明度)与[strokeStyle](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#strokestyle)(设置描边的颜色)等属性修改绘制内容的样式。将通过以下几个方面简单介绍画布组件常见使用方法:
160
161- 绘制基础形状。
162  可以通过[arc](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#arc)(绘制弧线路径)、 [ellipse](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#ellipse)(绘制一个椭圆)、[rect](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#rect)(创建矩形路径)等接口绘制基础形状。
163
164  ```ts
165  Canvas(this.context)
166    .width('100%')
167    .height('100%')
168    .backgroundColor('#F5DC62')
169    .onReady(() => {
170       //绘制矩形
171       this.context.beginPath();
172       this.context.rect(100, 50, 100, 100);
173       this.context.stroke();
174       //绘制圆形
175       this.context.beginPath();
176       this.context.arc(150, 250, 50, 0, 6.28);
177       this.context.stroke();
178       //绘制椭圆
179       this.context.beginPath();
180       this.context.ellipse(150, 450, 50, 100, Math.PI * 0.25, Math.PI * 0, Math.PI * 2);
181       this.context.stroke();
182    })
183  ```
184
185  ![2023022794521(1)](figures/2023022794521.jpg)
186
187- 绘制文本。
188
189  可以通过[fillText](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#filltext)(文本填充)、[strokeText](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#stroketext)(文本描边)等接口进行文本绘制,示例中设置了font为50像素高加粗的"sans-serif"字体,然后调用fillText方法在(50, 100)处绘制文本"Hello World!",设置strokeStyle为红色,lineWidth为2,font为50像素高加粗的"sans-serif"字体,然后调用strokeText方法在(50, 150)处绘制文本"Hello World!"的轮廓。
190
191  ```ts
192  Canvas(this.context)
193    .width('100%')
194    .height('100%')
195    .backgroundColor('#F5DC62')
196    .onReady(() => {
197      // 文本填充
198      this.context.font = '50px bolder sans-serif';
199      this.context.fillText("Hello World!", 50, 100);
200      // 文本描边
201      this.context.strokeStyle = "#ff0000"
202      this.context.lineWidth = 2
203      this.context.font = '50px bolder sans-serif';
204      this.context.strokeText("Hello World!", 50, 150);
205    })
206  ```
207
208  ![2023022795105(1)](figures/2023022795105.jpg)
209
210- 绘制文本边框。
211
212  可以通过[measureText](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#measuretext)(文本测量)计算绘制文本的宽度和高度,使用测量的宽度和高度作为边框的尺寸。在示例中,设置textBaseline为'top',font为30像素的"monospace"字体,通过measureText测量出文本的宽度和高度,然后调用fillText方法在(20, 100)处绘制文本"Hello World!",并调用strokeRect方法在同一位置使用测量的宽度和高度绘制相应尺寸的边框。接着,设置font为60像素的粗体"sans-serif"字体,再次通过measureText测量文本的宽度和高度,接着调用fillText方法在(20, 150)处绘制文本"Hello World!",并调用strokeRect方法在同一位置使用测量的宽度和高度绘制对应尺寸的边框。
213
214  ```ts
215  // xxx.ets
216  @Entry
217  @Component
218  struct measureTextAndRect {
219    drawText: string = "Hello World"
220    private settings: RenderingContextSettings = new RenderingContextSettings(true);
221    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
222
223    build() {
224      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
225        Canvas(this.context)
226          .width('100%')
227          .height('100%')
228          .backgroundColor('#F5DC62')
229          .onReady(() => {
230            // 文本的水平对齐方式为'top'
231            this.context.textBaseline = 'top'
232            // 文本字号为30px,字体系列为monospace
233            this.context.font = '30px monospace'
234            let textWidth = this.context.measureText(this.drawText).width
235            let textHeight = this.context.measureText(this.drawText).height
236            this.context.fillText(this.drawText, 20, 100)
237            this.context.strokeRect(20, 100, textWidth, textHeight)
238            // 文本字体粗细为粗体,字号为60px,字体系列为sans-serif
239            this.context.font = 'bold 60px sans-serif'
240            textWidth = this.context.measureText(this.drawText).width
241            textHeight = this.context.measureText(this.drawText).height
242            this.context.fillText(this.drawText, 20, 150)
243            this.context.strokeRect(20, 150, textWidth, textHeight)
244          })
245      }
246      .width('100%')
247      .height('100%')
248    }
249  }
250  ```
251
252  ![measureTextAndRect](figures/measureTextAndRect.png)
253
254- 使用自定义字体绘制文本。
255
256  从API version 20开始,可以通过[getGlobalInstance](../reference/apis-arkgraphics2d/js-apis-graphics-text.md#getglobalinstance)获取应用全局字体管理器的实例,然后使用[loadfontsync](../reference/apis-arkgraphics2d/js-apis-graphics-text.md#loadfontsync)接口从设置的路径中加载自定义字体并通过[font](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#font)(设置文本绘制中的字体样式)接口设置文本绘制中的字体样式,接着通过[fillText](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#filltext)(绘制填充类文本)、[strokeText](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#stroketext)(绘制描边类文本)等接口进行文本绘制。
257
258  ```ts
259  import { text } from '@kit.ArkGraphics2D';
260
261  @Entry
262  @Component
263  struct CustomFont {
264    private settings: RenderingContextSettings = new RenderingContextSettings(true);
265    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
266
267    build() {
268      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
269        Canvas(this.context)
270          .width('100%')
271          .height('100%')
272          .backgroundColor('#F5DC62')
273          .onReady(() => {
274            //加载自定义字体
275            let fontCollection = text.FontCollection.getGlobalInstance();
276            fontCollection.loadFontSync('customFont', $rawfile("customFont.ttf"))
277            this.context.font = '30vp customFont'
278            this.context.fillText("Hello World!", 20, 50)
279            this.context.strokeText("Hello World!", 20, 100)
280          })
281      }
282      .width('100%')
283      .height('100%')
284    }
285  }
286  ```
287
288  ![customFont](figures/customFont.jpeg)
289
290- 绘制图片和图像像素信息处理。
291
292  可以通过[drawImage](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#drawimage)(图像绘制)、[putImageData](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#putimagedata)(使用[ImageData](../reference/apis-arkui/arkui-ts/ts-components-canvas-imagedata.md)数据填充新的矩形区域)等接口绘制图片,通过[createImageData](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#createimagedata)(创建新的ImageData 对象)、[getPixelMap](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#getpixelmap)(以当前canvas指定区域内的像素创建[PixelMap](../reference/apis-image-kit/arkts-apis-image-PixelMap.md)对象)、[getImageData](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#getimagedata)(以当前canvas指定区域内的像素创建ImageData对象)等接口进行图像像素信息处理。
293
294  ```ts
295  @Entry
296  @Component
297  struct GetImageData {
298    private settings: RenderingContextSettings = new RenderingContextSettings(true);
299    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
300    private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600);
301    // "/common/images/1234.png"需要替换为开发者所需的图像资源文件
302    private img: ImageBitmap = new ImageBitmap("/common/images/1234.png");
303
304    build() {
305      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
306        Canvas(this.context)
307          .width('100%')
308          .height('100%')
309          .backgroundColor('#F5DC62')
310          .onReady(() => {
311            let offContext = this.offCanvas.getContext("2d", this.settings)
312            // 使用drawImage接口将图片画在(0,0)为起点,宽高130的区域
313            offContext.drawImage(this.img, 0, 0, 130, 130);
314            // 使用getImageData接口,获得canvas组件区域中,(50,50)为起点,宽高130范围内的绘制内容
315            let imageData = offContext.getImageData(50, 50, 130, 130);
316            // 使用putImageData接口将得到的ImageData画在起点为(150, 150)的区域中
317            offContext.putImageData(imageData, 150, 150);
318            // 将离屏绘制的内容画到canvas组件上
319            let image = this.offCanvas.transferToImageBitmap();
320            this.context.transferFromImageBitmap(image);
321          })
322      }
323      .width('100%')
324      .height('100%')
325    }
326  }
327  ```
328
329  ![drawimage](figures/drawimage.PNG)
330
331- 其他方法。
332
333  Canvas中还提供其他类型的方法。渐变([CanvasGradient](../reference/apis-arkui/arkui-ts/ts-components-canvas-canvasgradient.md)对象)相关的方法:[createLinearGradient](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#createlineargradient)(创建一个线性渐变色)、[createRadialGradient](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#createradialgradient)(创建一个径向渐变色)等。
334
335  ```ts
336  Canvas(this.context)
337    .width('100%')
338    .height('100%')
339    .backgroundColor('#F5DC62')
340    .onReady(() => {
341      //创建一个径向渐变色的CanvasGradient对象
342      let grad = this.context.createRadialGradient(200, 200, 50, 200, 200, 200)
343      //为CanvasGradient对象设置渐变断点值,包括偏移和颜色
344      grad.addColorStop(0.0, '#E87361');
345      grad.addColorStop(0.5, '#FFFFF0');
346      grad.addColorStop(1.0, '#BDDB69');
347      //用CanvasGradient对象填充矩形
348      this.context.fillStyle = grad;
349      this.context.fillRect(0, 0, 400, 400);
350    })
351  ```
352
353  ![2023022700701(1)](figures/2023022700701.jpg)
354
355## 使用状态变量驱动画布刷新
356
357可以使用状态变量来驱动Canvas刷新,将变化的数据通过@Watch监听,并绑定自定义的draw()方法。当数据刷新时,@Watch绑定的方法会执行绘制逻辑,使Canvas刷新。
358
359```ts
360@Entry
361@Component
362struct CanvasContentUpdate {
363  private settings: RenderingContextSettings = new RenderingContextSettings(true);
364  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
365  @State @Watch('draw')content: string = 'Hello World';
366
367  draw() {
368    this.context.clearRect(0, 0, 400, 200); // 清空Canvas的内容
369    this.context.fillText(this.content, 50, 100); // 重新绘制
370  }
371
372  build() {
373    Column() {
374      Canvas(this.context)
375        .width('100%')
376        .height('25%')
377        .backgroundColor('rgb(39, 135, 217)')
378        .onReady(() => {
379          this.context.font = '65px sans-serif';
380          this.context.fillText(this.content, 50, 100);
381        })
382      TextInput({
383        text:$$this.content // 修改文本输入框里的内容时,状态变量的更新会驱动Canvas刷新
384      })
385        .fontSize(35)
386    }
387    .width('100%')
388    .height('100%')
389  }
390}
391```
392
393![data_drive_update](figures/data_drive_update.gif)
394
395## 场景示例
396
397- 绘制规则基础形状。
398
399  ```ts
400  @Entry
401  @Component
402  struct ClearRect {
403    private settings: RenderingContextSettings = new RenderingContextSettings(true);
404    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
405
406    build() {
407      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
408        Canvas(this.context)
409          .width('100%')
410          .height('100%')
411          .backgroundColor('#F5DC62')
412          .onReady(() => {
413            // 设定填充样式,填充颜色设为蓝色
414            this.context.fillStyle = '#0097D4';
415            // 以(50, 50)为左上顶点,画一个宽高200的矩形
416            this.context.fillRect(50, 50, 200, 200);
417            // 以(70, 70)为左上顶点,清除宽150高100的区域
418            this.context.clearRect(70, 70, 150, 100);
419          })
420      }
421      .width('100%')
422      .height('100%')
423    }
424  }
425  ```
426
427  ![2023022701120(1)](figures/2023022701120.jpg)
428
429- 绘制不规则图形。
430
431  ```ts
432  @Entry
433  @Component
434  struct Path2d {
435    private settings: RenderingContextSettings = new RenderingContextSettings(true);
436    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
437
438    build() {
439      Row() {
440        Column() {
441          Canvas(this.context)
442            .width('100%')
443            .height('100%')
444            .backgroundColor('#F5DC62')
445            .onReady(() => {
446              // 使用Path2D的接口构造一个五边形
447              let path = new Path2D();
448              path.moveTo(150, 50);
449              path.lineTo(50, 150);
450              path.lineTo(100, 250);
451              path.lineTo(200, 250);
452              path.lineTo(250, 150);
453              path.closePath();
454              // 设定填充色为蓝色
455              this.context.fillStyle = '#0097D4';
456              // 使用填充的方式,将Path2D描述的五边形绘制在canvas组件内部
457              this.context.fill(path);
458            })
459        }
460        .width('100%')
461      }
462      .height('100%')
463    }
464  }
465  ```
466
467  ![2023032422159](figures/2023032422159.jpg)
468
469- 绘制可拖动的光标。
470
471  可以通过[beginPath](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#beginpath)、[moveTo](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#moveto)、[lineTo](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#lineto)和[arc](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#arc)方法设置光标的位置,使用[stroke](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#stroke)和[fill](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md#fill)方法绘制光标,将是否按下和位置变化通过@Watch监听,并绑定自定义的drawCursor()方法。当拖动光标时,@Watch绑定的方法会执行绘制逻辑,计算并更新光标的颜色和位置。
472
473  ```ts
474  @Entry
475  @Component
476  struct CursorMoving {
477    // 监听是否按下,刷新光标颜色
478    @State @Watch('drawCursor') isTouchDown: boolean = false
479    // 监听位置变化,刷新页面
480    @State @Watch('drawCursor') cursorPosition: RectPosition = {
481      x: 0,
482      y: 0,
483      width: 0,
484      height: 0,
485    }
486    private settings: RenderingContextSettings = new RenderingContextSettings(true);
487    private canvasContext: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
488    private sw: number = 360; // Canvas固定宽度
489    private sh: number = 270; // Canvas固定高度
490    private cursorWH: number = 50; // 光标区域宽高
491    private dashedLineW: number = 7; // 光标宽高
492    private arcRadius: number = 6; // 光标中心圆半径
493    private isReadyMove: boolean = false
494    private touchPosition: Position = {
495      x: 0,
496      y: 0,
497    };
498    private cursorCenterPosition: Position = {
499      x: 0,
500      y: 0,
501    };
502
503    build() {
504      Column() {
505        // 绘制光标
506        Canvas(this.canvasContext)
507          .width(this.sw)
508          .height(this.sh)
509          .backgroundColor('#D5D5D5')
510          .onReady(() => {
511            this.cursorPosition.x = (this.sw - this.cursorWH) / 2
512            this.cursorPosition.y = (this.sh - this.cursorWH) / 2
513            this.cursorPosition.width = this.cursorWH
514            this.cursorPosition.height = this.cursorWH
515            this.cursorCenterPosition = {
516              x: this.cursorPosition.x + this.cursorPosition.width / 2,
517              y: this.cursorPosition.y + this.cursorPosition.height / 2
518            }
519            this.drawCursor()
520          })
521          .onTouch(event => {
522            if (event.type === TouchType.Down) {
523              this.isReadyMove = this.isTouchCursorArea(event.touches[0]);
524              if (this.isReadyMove) {
525                this.isTouchDown = true
526              }
527
528              this.touchPosition = {
529                x: event.touches[0].displayX,
530                y: event.touches[0].displayY
531              }
532            } else if (event.type === TouchType.Move) {
533              if (this.isReadyMove) {
534                let moveX = event.changedTouches[0].displayX - this.touchPosition.x;
535                let moveY = event.changedTouches[0].displayY - this.touchPosition.y;
536                this.touchPosition = {
537                  x: event.changedTouches[0].displayX,
538                  y: event.changedTouches[0].displayY
539                }
540                this.cursorPosition.x += moveX;
541                this.cursorPosition.y += moveY;
542
543                this.cursorCenterPosition = {
544                  x: this.cursorPosition.x + this.cursorPosition.width / 2,
545                  y: this.cursorPosition.y + this.cursorPosition.height / 2
546                }
547                // 光标区域中心点位置限制
548                if (this.cursorCenterPosition.x < 0) {
549                  this.cursorPosition.x = -this.cursorPosition.width / 2
550                }
551                if (this.cursorCenterPosition.y < 0) {
552                  this.cursorPosition.y = -this.cursorPosition.height / 2
553                }
554                if (this.cursorCenterPosition.x > this.sw) {
555                  this.cursorPosition.x = this.sw - this.cursorPosition.width / 2
556                }
557                if (this.cursorCenterPosition.y > this.sh) {
558                  this.cursorPosition.y = this.sh - this.cursorPosition.height / 2
559                }
560              }
561            } else {
562              this.isTouchDown = false
563            }
564          })
565      }
566      .height('100%')
567      .width('100%')
568      .justifyContent(FlexAlign.Center)
569    }
570
571    // 绘制裁剪框
572    drawCursor() {
573      // 算出菱形四个点
574      let positionL: Position = { x: this.cursorPosition.x, y: this.cursorPosition.y + this.cursorPosition.height / 2 }
575      let positionT: Position = { x: this.cursorPosition.x + this.cursorPosition.width / 2, y: this.cursorPosition.y }
576      let positionR: Position = {
577        x: this.cursorPosition.x + this.cursorPosition.width,
578        y: this.cursorPosition.y + this.cursorPosition.height / 2
579      }
580      let positionB: Position = {
581        x: this.cursorPosition.x + this.cursorPosition.width / 2,
582        y: this.cursorPosition.y + this.cursorPosition.height
583      }
584      let lineWidth = 2
585      this.canvasContext.clearRect(0, 0, this.sw, this.sh);
586      this.canvasContext.lineWidth = lineWidth
587      this.canvasContext.strokeStyle = this.isTouchDown ? '#ff1a5cae' : '#ffffffff'
588
589      // 画出四角
590      this.canvasContext.beginPath()
591      this.canvasContext.moveTo(positionL.x + this.dashedLineW, positionL.y - this.dashedLineW);
592      this.canvasContext.lineTo(positionL.x, positionL.y);
593      this.canvasContext.lineTo(positionL.x + this.dashedLineW, positionL.y + this.dashedLineW);
594
595      this.canvasContext.moveTo(positionT.x - this.dashedLineW, positionT.y + this.dashedLineW);
596      this.canvasContext.lineTo(positionT.x, positionT.y);
597      this.canvasContext.lineTo(positionT.x + this.dashedLineW, positionT.y + this.dashedLineW);
598
599      this.canvasContext.moveTo(positionR.x - this.dashedLineW, positionR.y - this.dashedLineW);
600      this.canvasContext.lineTo(positionR.x, positionR.y);
601      this.canvasContext.lineTo(positionR.x - this.dashedLineW, positionR.y + this.dashedLineW);
602
603      this.canvasContext.moveTo(positionB.x - this.dashedLineW, positionB.y - this.dashedLineW);
604      this.canvasContext.lineTo(positionB.x, positionB.y);
605      this.canvasContext.lineTo(positionB.x + this.dashedLineW, positionB.y - this.dashedLineW);
606
607      this.canvasContext.stroke()
608
609      // 画出中心圆
610      this.canvasContext.beginPath()
611      this.canvasContext.strokeStyle = this.isTouchDown ? '#ff1a5cae' : '#ff9ba59b'
612      this.canvasContext.fillStyle = this.isTouchDown ? '#ff1a5cae' : '#ff9ba59b'
613      this.canvasContext.arc(this.cursorPosition.x + this.cursorPosition.width / 2,
614        this.cursorPosition.y + this.cursorPosition.width / 2, this.arcRadius, 0, 2 * Math.PI)
615      this.canvasContext.fill()
616      this.canvasContext.stroke()
617
618      // 画出四条线
619      this.canvasContext.beginPath();
620      this.canvasContext.lineWidth = 0.7;
621      this.canvasContext.moveTo(positionL.x, positionL.y);
622      this.canvasContext.lineTo(0, positionL.y);
623
624      this.canvasContext.moveTo(positionT.x, positionT.y);
625      this.canvasContext.lineTo(positionT.x, 0);
626
627      this.canvasContext.moveTo(positionR.x, positionR.y);
628      this.canvasContext.lineTo(this.sw, positionR.y);
629
630      this.canvasContext.moveTo(positionB.x, positionB.y);
631      this.canvasContext.lineTo(positionB.x, this.sh);
632
633      this.canvasContext.stroke();
634    }
635
636    // 判断点击位置是否在棱形中
637    isTouchCursorArea(touch: TouchObject) {
638      let tempLength = Math.sqrt((touch.x - this.cursorCenterPosition.x) * (touch.x - this.cursorCenterPosition.x) +
639        (touch.y - this.cursorCenterPosition.y) * (touch.y - this.cursorCenterPosition.y))
640      if (tempLength < (this.cursorWH / 2 / 1.414)) {
641        return true
642      }
643      return false
644    }
645  }
646
647  export interface RectPosition {
648    x: number;
649    y: number;
650    height: number;
651    width: number;
652  }
653
654  export interface Position {
655    x: number;
656    y: number;
657  }
658  ```
659
660  ![CursorMoving](./figures/CursorMoving.gif)
661
662## 相关实例
663
664使用画布绘制自定义图形,有以下相关实例可供参考:
665
666- [ArkTS组件集(ArkTS)(Full SDK)(API10)](https://gitcode.com/openharmony/applications_app_samples/tree/master/code/UI/ArkTsComponentCollection/ComponentCollection)
667
668- [分布式五子棋(ArkTS)(Full SDK)(API9)](https://gitcode.com/openharmony/applications_app_samples/tree/master/code/Solutions/Game/DistributedDataGobang)
669
670- [ArkTS时钟(ArkTS)(API9)](https://gitcode.com/openharmony/applications_app_samples/tree/master/code/Solutions/Tools/ArkTSClock)
671
672- [Lottie动画](https://gitcode.com/openharmony/applications_app_samples/tree/master/code/Solutions/Game/Lottie)
673
674- [自定义抽奖转盘(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/CanvasComponent)
675<!--RP1--><!--RP1End-->