Workshop › 2048 › Step 24 of 26

Swipes

What we are doing

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()
})
```

What it means

Your turn

Write the comment, swipeStart and the two listeners above function cellX(col) {, with an empty line after them.

Skills: Keyboard and mouse input

All steps

  1. The board
  2. Sixteen cells
  3. A grid of numbers
  4. A color for every number
  5. Numbers on the tiles
  6. Big numbers, smaller text
  7. Find the empty cells
  8. A new tile
  9. Two tiles to start
  10. Slide a row
  11. Merge equal tiles
  12. Move left
  13. The arrow key
  14. Only real moves count
  15. Right is left, reversed
  16. Up and down are columns
  17. Score
  18. Is there a move left?
  19. Game over
  20. Making 2048
  21. Win and lose screens
  22. Space to go on
  23. Best score
  24. Swipes
  25. A tap is not a swipe
  26. Build it yourself: undo