使用CanvasRenderingContext2D中的moveTo,lineTo等函数绘制各个部分的线条,最后将线条连接回起点完成翻角效果。
完整示例参考如下:
@Entry @Component struct Clip { private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); build() { Column() { Canvas(this.context) .height(200) .width('100%') .onReady(() => { this.context.moveTo(50, 0); this.context.quadraticCurveTo(55, 5, 55, 25); // 左上角向右下的弧线 this.context.lineTo(55, 40); // 竖直向下的竖线 this.context.arc(60, 40, 5, Math.PI, Math.PI / 2, true); // 左下角的半圆弧线 this.context.lineTo(75, 45); // 绘制水平横线 this.context.quadraticCurveTo(95, 45, 100, 50); // 右下角的弧线 this.context.lineTo(50, 0); let gradient = this.context.createLinearGradient(50, 50, 75, 75); gradient.addColorStop(0, '#ccc'); gradient.addColorStop(0.7, '#111'); gradient.addColorStop(1, '#000'); this.context.fillStyle = gradient; this.context.fill(); // 对封闭的路径进行填充 this.context.beginPath(); // 新建路径 this.context.moveTo(50, 0); this.context.lineTo(100, 50); this.context.lineTo(100, 0); this.context.lineTo(50, 0); this.context.closePath(); // 闭合路径 this.context.fillStyle = '#ff6600'; this.context.fill(); }); } .margin({ top: 200, left: 120 }) .width('100%') .height('100%') } }