参考如下demo:
@Entry
@Component
struct Page9 {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
@State @Watch('draw') positionXY : number[] = [0, 0]; // 原始坐标点
prePosition: number[] = []; // 上一次坐标点
clickXY: number[] = []; // 鼠标落下坐标点
shiftingPosition: number[] = []; // 偏移参照点
rectWidth: number = 100;
rectHeight: number = 100;
PanGestureFlag: boolean = false;
build() {
Column() {
Canvas(this.context)
.width('100%')
.height('50%')
.backgroundColor('#ffff00')
.margin({top: 50})
.onReady(() => {
this.draw()
})
.gesture( // 拖拽手势
PanGesture()
.onActionStart((event: GestureEvent) =>{
let x = event.fingerList[0].localX;
let y = event.fingerList[0].localY;
if(x >= this.positionXY[0] &&
x<= (this.positionXY[0] + this.rectWidth) &&
y > this.positionXY[1] &&
y<=(this.positionXY[1] + this.rectHeight)
){
this.PanGestureFlag = true; // 可以拖动
this.clickXY = [parseInt(`${x}`), parseInt(`${y}`)];
this.shiftingPosition = [...this.positionXY];
console.info(`shiftingPosition ${this.shiftingPosition}`)
}
})
.onActionUpdate((event: GestureEvent) =>{
if(this.PanGestureFlag) {
this.prePosition = [...this.positionXY]; // 保存上一次坐标
const x = this.shiftingPosition[0] + parseInt(`${event.offsetX}`);
const y = this.shiftingPosition[1] + parseInt(`${event.offsetY}`);
this.positionXY = [x, y];
console.log(`positionXY ${this.positionXY}`);
}
})
.onActionEnd(() =>{
this.PanGestureFlag = false; // 结束后,停止拖动
})
)
}
}
draw() {
this.context.reset();
if (this.prePosition.length) {
this.context.clearRect(this.prePosition[0], this.prePosition[1], this.rectWidth, this.rectHeight);
}
this.context.fillRect(this.positionXY[0], this.positionXY[1], this.rectWidth, this.rectHeight)
}
}