Workshop › 2048 › Step 24 of 26
2048 is at its best on a phone, played with swipes. A swipe is built from two events: remember where the finger went down, and on the way up measure how far it moved. The bigger of the two distances decides the direction.
```js
// A swipe is where the pointer came up compared to where it went down.
let swipeStart = null
canvas.addEventListener('pointerdown', (event) => {
swipeStart = { x: event.clientX, y: event.clientY }
})
canvas.addEventListener('pointerup', (event) => {
if (!swipeStart) return
const dx = event.clientX - swipeStart.x
const dy = event.clientY - swipeStart.y
swipeStart = null
if (Math.abs(dx) > Math.abs(dy)) move(dx > 0 ? 'right' : 'left')
else move(dy > 0 ? 'down' : 'up')
draw()
})
```pointerdown stores the start point; pointerup works out dx and dy and forgets the start.Math.abs drops the sign, so the bigger movement wins; the sign of that one picks the direction.Write the comment, swipeStart and the two listeners above function cellX(col) {, with an empty line after them.
Skills: Keyboard and mouse input
← Best score A tap is not a swipe →