1# 卡片使用自定义绘制能力 2 3 4ArkTS卡片开放了自定义绘制的能力,在卡片上可以通过[Canvas](../reference/apis-arkui/arkui-ts/ts-components-canvas-canvas.md)组件创建一块画布,然后通过[CanvasRenderingContext2D](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md)对象在画布上进行自定义图形的绘制,如下示例代码实现了在画布的中心绘制了一个笑脸。 5 6```ts 7@Entry 8@Component 9struct CustomCanvasDrawingCard { 10 private canvasWidth: number = 0; 11 private canvasHeight: number = 0; 12 // 初始化CanvasRenderingContext2D和RenderingContextSettings 13 private settings: RenderingContextSettings = new RenderingContextSettings(true); 14 private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); 15 16 build() { 17 Column() { 18 Row() { 19 Canvas(this.context) 20 .width('100%') 21 .height('100%') 22 .onReady(() => { 23 // 在onReady回调中获取画布的实际宽和高 24 this.canvasWidth = this.context.width; 25 this.canvasHeight = this.context.height; 26 // 绘制画布的背景 27 this.context.fillStyle = '#EEF0FF'; 28 this.context.fillRect(0, 0, this.canvasWidth, this.canvasHeight); 29 // 在画布的中心绘制一个圆 30 this.context.beginPath(); 31 let radius = this.context.width / 3; 32 let circleX = this.context.width / 2; 33 let circleY = this.context.height / 2; 34 this.context.moveTo(circleX - radius, circleY); 35 this.context.arc(circleX, circleY, radius, 2 * Math.PI, 0, true); 36 this.context.closePath(); 37 this.context.fillStyle = '#5A5FFF'; 38 this.context.fill(); 39 // 绘制笑脸的左眼 40 let leftR = radius / 13; 41 let leftX = circleX - (radius / 2.3); 42 let leftY = circleY - (radius / 4.5); 43 this.context.beginPath(); 44 this.context.arc(leftX, leftY, leftR, 0, 2 * Math.PI, true); 45 this.context.closePath(); 46 this.context.strokeStyle = '#FFFFFF'; 47 this.context.lineWidth = 15; 48 this.context.stroke(); 49 // 绘制笑脸的右眼 50 let rightR = radius / 13; 51 let rightX = circleX + (radius / 2.3); 52 let rightY = circleY - (radius / 4.5); 53 this.context.beginPath(); 54 this.context.arc(rightX, rightY, rightR, 0, 2 * Math.PI, true); 55 this.context.closePath(); 56 this.context.strokeStyle = '#FFFFFF'; 57 this.context.lineWidth = 15; 58 this.context.stroke(); 59 // 绘制笑脸的鼻子 60 let startX = circleX; 61 let startY = circleY - 20; 62 this.context.beginPath(); 63 this.context.moveTo(startX, startY); 64 this.context.lineTo(startX - 8, startY + 40); 65 this.context.lineTo(startX + 8, startY + 40); 66 this.context.strokeStyle = '#FFFFFF'; 67 this.context.lineWidth = 15; 68 this.context.lineCap = 'round'; 69 this.context.lineJoin = 'round'; 70 this.context.stroke(); 71 // 绘制笑脸的嘴巴 72 let mouthR = radius / 2; 73 let mouthX = circleX; 74 let mouthY = circleY + 10; 75 this.context.beginPath(); 76 this.context.arc(mouthX, mouthY, mouthR, Math.PI / 1.4, Math.PI / 3.4, true); 77 this.context.strokeStyle = '#FFFFFF'; 78 this.context.lineWidth = 15; 79 this.context.stroke(); 80 this.context.closePath(); 81 }) 82 } 83 }.height('100%').width('100%') 84 } 85} 86``` 87 88运行效果如下图所示。 89