TExcelTAD
Home › 2D Games with JavaScript & Canvas › Screen Shake & Hit Stop

Screen Shake & Hit Stop

When something heavy happens (an explosion, a boss slam, the player taking damage) a tiny shake of the whole screen makes the player feel it. A short hit stop, where the action freezes for a few hundredths of a second, makes a hit feel solid. Both are classic "game feel" tricks: they cost a few lines of code and change nothing in the game rules.

The trauma model

A naive shake moves the camera by a random amount for a fixed time. It works, but several hits in a row don't add up, and the shake stops abruptly. A popular, better approach is the trauma model:

  • The game keeps one number, trauma, between 0 and 1.
  • Each hit adds trauma (trauma = min(1, trauma + amount)), so hits stack but never exceed the maximum.
  • Trauma decays linearly over time, for example by 1.5 per second.
  • The actual shake strength is trauma² (or trauma³). Squaring makes small trauma almost invisible and big trauma dramatic, and the shake fades out smoothly.
  • The offset each frame is maxOffset × shake × random(-1..1), separately for x and y, plus optionally a small rotation.
js · try it yourself
const MAX_OFFSET = 12;   // pixels at full trauma
const DECAY = 1.5;       // trauma lost per second
let trauma = 0;

const addTrauma = (amount) => { trauma = Math.min(1, trauma + amount); };
const shake = () => trauma * trauma;

addTrauma(0.5);
addTrauma(0.3);          // two quick hits stack
console.log('after two hits:', trauma.toFixed(2));
addTrauma(0.6);          // a third would go past 1
console.log('clamped:', trauma.toFixed(2));

console.log('time  trauma  shake  max px');
for (let step = 0; step <= 6; step++) {
  const t = step * 0.125;
  console.log(t.toFixed(3), ' ', trauma.toFixed(2), '  ', shake().toFixed(2), ' ', (MAX_OFFSET * shake()).toFixed(1));
  trauma = Math.max(0, trauma - DECAY * 0.125);
}
after two hits: 0.80
clamped: 1.00
time  trauma  shake  max px
0.000   1.00    1.00   12.0
0.125   0.81    0.66   7.9
0.250   0.63    0.39   4.7
0.375   0.44    0.19   2.3
0.500   0.25    0.06   0.8
0.625   0.06    0.00   0.0
0.750   0.00    0.00   0.0

Look at the last column: the offset halves long before trauma does. That non-linear fade-out is what makes this model feel natural.

Applying the shake

Shake belongs to the camera, not to the objects. Before drawing the world, translate the context by the offset; after drawing it, restore the context and draw the HUD, so the score and health bar stay steady and readable:

js
ctx.save();
ctx.translate(Math.round(ox), Math.round(oy));   // integer pixels: no blurry edges
drawWorld();
ctx.restore();
drawHud();                                        // not shaken

Rounding to whole pixels matters for pixel art: a translation of 3.4 pixels makes every sprite edge blur over two pixels.

Hit stop

Hit stop (also called hit freeze or hitlag) pauses the game world for 50–100 ms when a hit lands. Fighting games use it on every punch. Implement it with a timer: while the timer is positive, update counts it down and returns early, so nothing moves. The shake keeps decaying during the freeze, so the screen still trembles.

Playable demo

Press Space to punch the sliding block. Each punch adds trauma and knocks the block back. Press H to toggle hit stop and T to turn shake off, and feel the difference.

html · try it yourself
<style>
  html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
  canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set();   // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
  if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
  if (!e.repeat) pressed.add(e.code);
  keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
  ctx.save();
  ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
  ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
  ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
  ctx.restore();
}
function run(update, draw, help = '') {
  const STEP = 1 / 60;
  let acc = 0, last = performance.now();
  requestAnimationFrame(function frame(now) {
    const dt = Math.min((now - last) / 1000, 0.1);
    last = now;
    if (active) {
      acc += dt;
      while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
      draw();
    } else if (!idleDrawn) {
      draw(); banner('Click to play', help); idleDrawn = true;
    }
    requestAnimationFrame(frame);
  });
}
// ---- end of play kit ----

const MAX_OFFSET = 10, MAX_ANGLE = 0.03, DECAY = 1.6;
let trauma = 0, freeze = 0, flash = 0;
let hitStop = true, shakeOn = true, hits = 0;
const enemy = { x: 240, vx: 90, kick: 0 };

function update(dt) {
  if (pressed.has('KeyH')) hitStop = !hitStop;
  if (pressed.has('KeyT')) shakeOn = !shakeOn;
  trauma = Math.max(0, trauma - DECAY * dt);   // shake keeps fading even during hit stop
  flash = Math.max(0, flash - dt);
  if (freeze > 0) { freeze -= dt; return; }     // hit stop: the world is frozen

  if (pressed.has('Space')) {
    hits++;
    trauma = Math.min(1, trauma + 0.45);
    flash = 0.08;
    if (hitStop) freeze = 0.07;
    enemy.kick = enemy.vx > 0 ? 420 : -420;     // knock it back
  }
  enemy.x += (enemy.vx + enemy.kick) * dt;
  enemy.kick *= 1 - 6 * dt;
  if (enemy.x < 60 || enemy.x > W - 60) {
    enemy.vx = -enemy.vx;
    enemy.kick = -enemy.kick;
    enemy.x = Math.max(60, Math.min(W - 60, enemy.x));
  }
}

function drawWorld() {
  ctx.fillStyle = '#1b2033';
  ctx.fillRect(-20, -20, W + 40, H + 40);       // oversized so shaking never shows the edge
  ctx.fillStyle = '#2c3350';
  for (let x = 0; x < W; x += 40) ctx.fillRect(x, 200, 20, 70);
  ctx.fillStyle = flash > 0 ? '#ffffff' : '#ef5350';
  ctx.fillRect(Math.round(enemy.x - 20), 150, 40, 50);
  ctx.fillStyle = '#ffb74d';
  ctx.fillRect(40, 160, 24, 40);
}

function draw() {
  const s = shakeOn ? trauma * trauma : 0;
  const ox = MAX_OFFSET * s * (Math.random() * 2 - 1);
  const oy = MAX_OFFSET * s * (Math.random() * 2 - 1);
  const angle = MAX_ANGLE * s * (Math.random() * 2 - 1);
  ctx.fillStyle = '#000';
  ctx.fillRect(0, 0, W, H);
  ctx.save();
  ctx.translate(W / 2, H / 2);                  // rotate around the screen centre
  ctx.rotate(angle);
  ctx.translate(Math.round(-W / 2 + ox), Math.round(-H / 2 + oy));
  drawWorld();
  ctx.restore();

  // HUD: drawn after restore, so it does not shake
  ctx.fillStyle = '#fff';
  ctx.font = '12px monospace';
  ctx.textAlign = 'left';
  ctx.fillText(`hits ${hits}  trauma ${trauma.toFixed(2)}`, 8, 16);
  ctx.fillText(`[H] hit stop ${hitStop ? 'ON' : 'off'}  [T] shake ${shakeOn ? 'ON' : 'off'}`, 8, 32);
}

run(update, draw, 'Space punches, H hit stop, T shake');
</script>

Use it with care

Do Don't
Scale trauma with the event: 0.2 for a small hit, 0.6 for an explosion Shake on every footstep or every bullet
Keep the HUD still Shake menus or text the player must read
Offer a "screen shake" option (on/off or a slider) Force it on players who get motion sickness
Use smooth noise for long rumbles (earthquake) Shake for seconds at full strength

Tip: Random offsets every frame give a sharp, jittery shake, good for impacts. For a slower rumble, sample a smooth noise function (Perlin or a sum of sine waves) with time instead of Math.random().

Note: A shake setting is an accessibility feature, not a luxury. The Settings & Saving lesson shows how to store it.

Test yourself

In the trauma model, why is the shake strength trauma * trauma instead of trauma?

  1. It is faster to compute
  2. Small trauma becomes barely visible and the shake fades out smoothly
  3. It makes the shake last longer
  4. Canvas requires squared values

Where should the HUD be drawn relative to the shake?

  1. Inside the shaken transform, so it matches the world
  2. After ctx.restore(), so it stays steady
  3. Before clearing the canvas
  4. In a separate requestAnimationFrame loop

How is hit stop usually implemented?

  1. setTimeout that blocks the main thread
  2. A timer: while it is positive, update counts it down and returns early
  3. Lowering the frame rate to 10 FPS
  4. Skipping draw() for a second