想要做到图案的移动,可以利用画布中的clearRect方法。每当触发滑动事件时先获取画布中原来的图案,再通过clearRect方法清空当前的画布,将图案按照新的位置绘制。
@Entry @Component struct CanvasPage { private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); @State cX: number = 100; @State cY: number = 100; @State startX: number = 0; @State startY: number = 0; upDate(x: number, y: number) { this.context.clearRect(0, 0, 400, 400); this.context.beginPath(); this.context.arc(this.cX + x - this.startX, this.cY + y - this.startY, 50, 0, Math.PI * 2); this.context.lineWidth = 2; this.context.stroke(); } build() { Column() { Canvas(this.context) .onReady(() => { this.context.beginPath(); this.context.arc(this.cX, this.cY, 50, 0, Math.PI * 2); this.context.lineWidth = 2; this.context.stroke(); }) .onTouch((e) => { if (e.type === TouchType.Down) { this.startX = e.touches[0].x; this.startY = e.touches[0].y; } if (e.type === TouchType.Move) { this.upDate(e.touches[0].x, e.touches[0].y); } if (e.type === TouchType.Up) { this.cX = this.cX + e.touches[0].x - this.startX; this.cY = this.cY + e.touches[0].y - this.startY; } }) .width(300) .height(300) .backgroundColor('#f1f3f5') .borderRadius(6); } .height('100%') .width('100%'); } }