Card games live and die by their animations. This demo builds the complete visual layer for a card battle game — 3D card flip with face/back reveal, attack slash effect, card draw, HP bar drain, and a turn-based rhythm. All Canvas 2D, no libraries. Use this as the visual foundation for any HTML5 TCG, deckbuilder, or Hearthstone-style game.
A Canvas card battle scene with two opponents, animated card hands, a 3D flip effect using the horizontal scale trick (no WebGL needed), a lightning slash attack, and a hit shake effect. The demo cycles through draw → flip → attack → damage automatically. Click to play cards yourself.
Card Battle UI — JavaScript Canvas
How the card flip animation works in Canvas
The 3D flip is a scale trick — no WebGL required. Call ctx.scale(flipScale, 1) before drawing the card. As flipScale goes from 1 → 0, the card horizontally compresses until it disappears. Swap which face is drawn at scale 0, then animate back from 0 → 1. The result is an apparent 3D rotation achieved entirely with 2D canvas scaling.
// 3D card flip illusion with ctx.scale
function drawCard(x, y, w, h, card, flipScale) {
ctx.save();
ctx.translate(x + w / 2, y + h / 2);
ctx.scale(flipScale, 1); // horizontal squeeze = flip illusion
ctx.translate(-(x + w / 2), -(y + h / 2));
// Show front if scale is positive, back if negative
const showFront = flipScale >= 0;
if (showFront) drawCardFront(ctx, card, x, y, w, h);
else drawCardBack(ctx, card, x, y, w, h);
ctx.restore();
}
One ctx.scale() call fakes a 3D card flip. No WebGL, no CSS 3D transforms — just 2D canvas math.
Building the full card battle system
The battle runs as a state machine: idle → flip → attack → enemyAI → idle. Each state has a timer and transitions when the timer completes. The AI is simple: after the player's attack resolves, the enemy automatically attacks back with a random damage value. This two-state exchange is the core loop of every turn-based card game.
Add a deck as an array shuffled with Fisher-Yates. Add mana cost to each card and a mana bar. Add special card effects: fire cards deal 2× to ice, ice cards freeze for one turn, thunder ignores defense. Add an animation queue so effects chain smoothly. Add a mulligan screen at the start. Each feature is 10–30 lines on this foundation.
No comments:
Post a Comment