Add touch support to pathfinding canvas
Register touch event handlers (touchstart, touchmove, touchend) that call existing mouse handlers and prevent default scrolling (passive: false) so the canvas can be interacted with on touch devices. Update getGridPosition to accept TouchEvent or MouseEvent, read touch coordinates, and apply canvas-to-CSS scaling (canvas.width/rect.width and canvas.height/rect.height) to correctly map client coordinates to grid cells. This enables accurate touch interaction and handles high-DPI / CSS-scaled canvases.
This commit is contained in:
@@ -79,6 +79,20 @@ export class PathfindingComponent implements AfterViewInit {
|
||||
el.addEventListener('mousemove', (e) => this.onMouseMove(e));
|
||||
el.addEventListener('mouseup', () => this.onMouseUp());
|
||||
el.addEventListener('mouseleave', () => this.onMouseUp());
|
||||
|
||||
el.addEventListener('touchstart', (e) => {
|
||||
if(e.cancelable) e.preventDefault();
|
||||
this.onMouseDown(e as never);
|
||||
}, { passive: false });
|
||||
|
||||
el.addEventListener('touchmove', (e) => {
|
||||
if(e.cancelable) e.preventDefault();
|
||||
this.onMouseMove(e as never);
|
||||
}, { passive: false });
|
||||
|
||||
el.addEventListener('touchend', () => {
|
||||
this.onMouseUp();
|
||||
});
|
||||
}
|
||||
|
||||
applyGridSize(skipReset?: boolean): void {
|
||||
@@ -497,10 +511,26 @@ export class PathfindingComponent implements AfterViewInit {
|
||||
}
|
||||
|
||||
// Mouse -> grid cell
|
||||
private getGridPosition(event: MouseEvent): GridPos | null {
|
||||
const rect = this.canvas.nativeElement.getBoundingClientRect();
|
||||
const x = event.clientX - rect.left;
|
||||
const y = event.clientY - rect.top;
|
||||
private getGridPosition(event: MouseEvent | TouchEvent): GridPos | null {
|
||||
const canvas = this.canvas.nativeElement;
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
|
||||
let clientX, clientY;
|
||||
if (event instanceof MouseEvent) {
|
||||
clientX = event.clientX;
|
||||
clientY = event.clientY;
|
||||
} else if (event instanceof TouchEvent && event.touches.length > 0) {
|
||||
clientX = event.touches[0].clientX;
|
||||
clientY = event.touches[0].clientY;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
const scaleX = canvas.width / rect.width;
|
||||
const scaleY = canvas.height / rect.height;
|
||||
|
||||
const x = (clientX - rect.left) * scaleX;
|
||||
const y = (clientY - rect.top) * scaleY;
|
||||
|
||||
const col = Math.floor(x / this.nodeSize);
|
||||
const row = Math.floor(y / this.nodeSize);
|
||||
|
||||
Reference in New Issue
Block a user