Advertisement

HTML5 Canvas Stick Hero Game

| by Vladimir | 2 min read | code by Hunor Marton Borbely
Advanced

Tech & Dependencies

HTML CSS JavaScript

Features

  • State Machine
  • Procedural Generation
  • Render Loop

Browser Support

Chrome 60+ Edge 79+ Firefox 55+ Safari 11+

Core

This is an HTML5 Canvas Stick Hero Game. It uses pure JavaScript and mathematical rendering to create an interactive 2D physics puzzle. The function is to demonstrate a continuous render loop controlled by user input timing, transforming simple mouse holds into spatial calculations.

Specs

  • Weight: ~8 KB. No frameworks. Zero external dependencies.
  • Performance: Native 60 FPS. Relies entirely on window.requestAnimationFrame for hardware-accelerated repaints.
  • Theming / Customization: Centralized configuration variables (stretchingSpeed, walkingSpeed, background gradients).
  • Responsiveness: Fluid. Captures window.innerWidth/innerHeight and recalculates geometry on the resize event.
  • Web APIs: HTML Canvas 2D Context.
  • Graceful Degradation: Fails to a blank screen if JavaScript or Canvas is disabled. Requires modern ES6 support (destructuring, arrow functions).

Anatomy

The architecture separates the DOM overlays from the rendering engine.

  • HTML (The Skeleton): A raw <canvas id="game"> element overlayed with standard div nodes for scores and textual states.
  • CSS (The Skin): Structural absolute positioning. It handles the UI layers (score, restart button) while keeping the canvas full-screen and unstyled.
  • JS (The Nervous System): A custom state machine. It handles object initialization (platforms, background), calculates physics (velocity, angle, collision), and forces the canvas context to clear and redraw every frame based on the current timestamp.

Logic

The core logic is driven by a precise state machine inside the render loop. This is the Glyph-logic that defines every interaction frame by frame.

  switch (phase) {
    case "waiting":
      return; // Stop the loop
    case "stretching": {
      sticks.last().length += (timestamp - lastTimestamp) / stretchingSpeed;
      break;
    }
    case "turning": {
      sticks.last().rotation += (timestamp - lastTimestamp) / turningSpeed;
      // ...collision and state switch

Instead of chaotic setTimeouts, the game observes a strict phase variable (waiting, stretching, turning, walking, transitioning, falling). The physics are decoupled from frame rates by multiplying velocity by (timestamp - lastTimestamp). This ensures consistent physics whether the display runs at 60Hz or 144Hz.

Feel

Tension and gravity. The mechanic requires focus. Holding the mouse down provides immediate visual feedback as the line extends. Releasing it triggers a rigid mathematical outcome — success or failure based on exact pixel boundaries. The motion is smooth, predictable, and strictly controlled by the underlying geometry.

Advertisement