/** * 专注画各种图形 */ @Component export struct Draw{ private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) /** * 画的范围 */ @Prop drawWidth:number=100 @Prop drawHeight:number=100 startWidth:number=0 startHeight:number=0 /** * 定点数组, * 比如想画一个三角形 */ @Prop drawArr:number[][]=[[50,0],[100,100],[0,100]] // @Prop drawArrX:number[]=[] // @Prop drawArrY:number[]=[] private drawCircleWithCustomRadii() { // this.context.clearRect(0,0,0,0) this.context.clearRect(0, 0, this.drawWidth, this.drawHeight); // 清空Canvas的内容 this.drawArr.forEach((item:number[],index:number)=>{ this.context.beginPath() this.context.moveTo(this.drawArr[index][0], this.drawArr[index][1]) if(index!=this.drawArr.length-1) { this.context.lineTo(this.drawArr[index+1][0], this.drawArr[index+1][1]) }else{ this.context.moveTo(this.drawArr[0][0], this.drawArr[0][1]) } this.context.strokeStyle = '#efd4f9' // 红色半径线 this.context.lineWidth = 1.5 this.context.stroke() }) // const radius = 125 // 圆半径 // 根据自定义角度数组绘制半径线 // this.cells.forEach(angle => { // // 将角度转换为弧度(Canvas使用弧度制) // const radians = (angle.angleEnd-90) * Math.PI / 180 // // // 计算半径线终点坐标 // const endX = centerX + radius * Math.cos(radians) // const endY = centerY + radius * Math.sin(radians) // // // 绘制半径线 // this.context.beginPath() // this.context.moveTo(centerX, centerY) // this.context.lineTo(endX, endY) // this.context.strokeStyle = '#efd4f9' // 红色半径线 // this.context.lineWidth = 1.5 // this.context.stroke() // // // // 标注角度值(修正后的文本绘制方式) // // this.context.font = '12px sans-serif' // // this.context.fillStyle = '#000000' // // this.context.textAlign = 'center' // // this.context.textBaseline = 'middle' // // // // 文本位置稍微向外偏移 // // const textRadius = radius + 15 // // const textX = centerX + textRadius * Math.cos(radians) // // const textY = centerY + textRadius * Math.sin(radians) // // // 使用fillText绘制文本 // // this.context.fillText(`${angle}°`, textX, textY) // }) } aboutToAppear(): void { // this.drawCircleWithCustomRadii() } build() { Column(){ Canvas(this.context) .width(this.drawWidth) .height(this.drawHeight) .backgroundColor(Color.Transparent) .onReady(() => { this.drawCircleWithCustomRadii() }) }.width(this.drawWidth) .height(this.drawHeight) } }