From 854c975cd0dfa53369956a7e12695a562a13124e Mon Sep 17 00:00:00 2001 From: arne Date: Mon, 25 Mar 2024 07:59:25 +0100 Subject: [PATCH] client: handle touch events properly --- client/src/main.ts | 38 ++++++++++++++++++++++++++++++++------ 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/client/src/main.ts b/client/src/main.ts index 74da642..e752664 100644 --- a/client/src/main.ts +++ b/client/src/main.ts @@ -47,15 +47,28 @@ const makeRipple = (position: [number, number], radius: number): void => { // event handlers +const throttle = (fn: (...x: X[]) => Y, ms: number) => { + let lastExecutedAt = -1 + return (...x: X[]) => { + const now = Date.now() + if (now - lastExecutedAt > ms) { + lastExecutedAt = now + fn(...x) + } + } +} + +const at60fps = (fn: (...x: X[]) => Y) => throttle(fn, 1000 / 60) + // create a big ripple when touching the screen -canvas.addEventListener('mousedown', (e) => { +canvas.addEventListener('mousedown', at60fps((e) => { // TODO Normalize x and y coords const radius = MAX_RADIUS makeRipple([ e.clientX / window.innerWidth, e.clientY / window.innerHeight ], radius) -}) +})) // create a smaller ripple when moving over the screen function* minDist(dist: number) { @@ -73,7 +86,7 @@ function* minDist(dist: number) { const hasSpace = minDist(MAX_RADIUS / 6) -canvas.addEventListener('mousemove', (e) => { +canvas.addEventListener('mousemove', at60fps((e) => { const shouldSpawn = hasSpace.next().value! if (shouldSpawn([e.clientX, e.clientY])) { const radius = MAX_RADIUS / 3*2 @@ -82,10 +95,23 @@ canvas.addEventListener('mousemove', (e) => { e.clientY / window.innerHeight ], radius) } -}) +})) + +canvas.addEventListener('touchmove', at60fps((e) => { + const shouldSpawn = hasSpace.next().value! + const radius = MAX_RADIUS / 3*2 + for (const touch of e.touches) { + if (shouldSpawn([touch.clientX, touch.clientY])) { + makeRipple([ + touch.clientX / window.innerWidth, + touch.clientY / window.innerHeight + ], radius) + } + } +})) // react to incoming websocket messages -socket.addEventListener('message', (e) => { +socket.addEventListener('message', at60fps((e) => { console.log('Received websocket message', e) if (typeof e.data === 'string') { // TODO: Validate message shape @@ -107,7 +133,7 @@ socket.addEventListener('message', (e) => { } else { console.warn('i received an odd message and i don\'t know what to do with it', e.data) } -}) +})) // main loop