Workshop › Memory › Step 24 of 25

Animate the turn

What we are doing

To fake a 3D turn in 2D we squeeze the card horizontally. As flip goes from 0 to 1, Math.abs(Math.cos(flip * π)) goes 1 → 0 → 1: full width, a thin line halfway (exactly when the sides swap), full width again.

```js
// Squeeze the card horizontally to fake a 3D turn: full width, a thin line halfway, full width again.
const width = CARD * Math.abs(Math.cos(card.flip * Math.PI))
const x = cardX(card) + (CARD - width) / 2
const y = cardY(card)
if (card.flip >= 0.5) {
  ctx.fillStyle = card.matched ? '#bbf7d0' : '#f8fafc'
  ctx.fillRect(x, y, width, CARD)
  ctx.fillText(card.symbol, cardX(card) + CARD / 2, y + CARD / 2)
} else {
  ctx.fillStyle = '#6366f1'
  ctx.fillRect(x, y, width, CARD)
}
```

What it means

Your turn

In draw's card loop, add the comment and width line, change x, and use width in both fillRects and cardX(card) in fillText.

Skills: The game loop, Drawing on a canvas

All steps

  1. Get the canvas and the pen
  2. The table
  3. One card
  4. A row of cards
  5. Four rows
  6. Every fruit twice
  7. Cards that know themselves
  8. A card's corner
  9. Draw the cards from the list
  10. Draw again and again
  11. The face of a card
  12. A fair shuffle
  13. Which card is at a point?
  14. Click to turn a card
  15. One place for the rules
  16. Two cards at a time
  17. Pair or no pair
  18. Count the moves
  19. Show moves and pairs
  20. All pairs found
  21. Play again
  22. A number that follows
  23. Swap sides halfway
  24. Animate the turn
  25. Build it yourself: your best game