← Coding with Art

Snow

This snowy night is made only from the code below. Tap the left or right side of it for a gust of wind, or open Snow controls at the bottom of it. Tap ⛶ Big to see it full screen. Tap the Try buttons to change the code, or type in it yourself.

The code HTML, CSS and JavaScript

The big picture

Same shape as the fireworks: update (move every flake a little), draw (paint the scene), repeat. Everything lives in one list, flakes, and each flake is a small object with its own numbers.

One difference from the fireworks: here dt means seconds since the last frame, and speeds are written as pixels per second. Fireworks used step, a frame count. Both make the show run at the same speed on any screen.

Part 1: The settings

var CFG = { flakes: 160, fallSpeed: 1, size: 1, wind: 0, sway: 1, scene: 'Night' };

A box of numbers the sliders change while the page runs.

Try: set flakes: 500 and wind: 2. That's a blizzard.

Part 2: Scenes

'Night': { top:'#0a1024', bottom:'#1c2a4d', ground:'#eef3fb', back:'#c4d1e6', stars:1, moon:true }

A scene is only colors. top and bottom are the sky gradient, ground is the front hill, and back is the hill behind it. stars is how bright the stars are (0 means none), and moon turns the moon on.

This changes scene: 'Night' in the settings, so the show starts with that scene.

To make a new scene, copy one line, rename it, and change the colors. It shows up in the dropdown on its own.

Try: add 'Pink morning': { top:'#6b3a73', bottom:'#ffb8a8', ground:'#fff', back:'#f2d4dc', stars:0, moon:false }.

After you add it, open Snow controls on the picture and pick Pink morning from the Scene menu.

Part 3: Canvas and hills

  • canvas is the board, ctx is the pen, and W and H are the screen size.
  • u is the size unit. Writing 34 * u instead of 34 keeps everything in proportion on a phone or a laptop.
  • groundY is H * 0.8, where the ground sits.
  • The hills are sine waves:
function hillFront(x) { return groundY + (Math.sin(x * k * 1.3) * 12 + ...) * u; }

Give it an x position, get back a height. k = 6.2832 / W makes the wave repeat across the screen width. Two sine waves added together (one slow, one fast) make a bumpy hill instead of a perfect wave.

Try: change the 12 to 40 and the hills get much taller.

Part 4: The snowflakes

A flake is an object:

{ x, y, z, r, vy, ph, sp }
  • x, y: position.
  • z: depth, from 0.3 (far) to 1 (close). This one number is what makes it feel 3D. Close flakes are bigger and fall faster, and far flakes are smaller, slower, and dimmer.
  • r: base size.
  • vy: base fall speed.
  • ph and sp: the start point and speed of the side-to-side wobble. Random values make every flake wobble differently, so they don't move in sync.

makeFlake(fromTop) builds one. At the start flakes appear at random heights (so the screen is already snowing), and later ones start above the top edge.

Part 5: The update

  1. Match the slider: if there are fewer flakes than CFG.flakes, add some. If there are more, remove some. That's why dragging the slider adds or removes snow instantly.
  2. Fall:
    f.y += f.vy * f.z * CFG.fallSpeed * u * dt;
    Speed times depth times the slider, times the time passed. Multiplying by dt is what keeps it smooth.
  3. Sway and wind:
    f.x += (windNow * f.z + Math.sin(time * f.sp + f.ph) * CFG.sway * 25 * u * f.z) * dt;
    Two parts add together. windNow * f.z is the wind, so close flakes get pushed harder. The Math.sin(...) part swings from left to right and back, which makes the gentle drifting.
  4. The gust: gust *= Math.exp(-dt * 1.2) shrinks the gust a little each frame, so it fades out smoothly instead of stopping suddenly. A tap adds to gust, and windNow is the wind slider plus the gust.
  5. Wrap around: a flake that leaves the right edge comes back on the left.
  6. Landing: if a flake reaches the front hill (f.y > hillFront(f.x)), it gets replaced by a new flake at the top. That's the whole recycling loop, so the snow never runs out.

Try: change 1.2 in Math.exp(-dt * 1.2) to 0.3. Gusts last much longer.

Then tap one side of the picture and watch the snow keep blowing.

Part 6: The drawing

Drawn back to front, like layers of paper:

  1. Sky: a vertical gradient from top to bottom.
  2. Stars: small squares that twinkle with Math.sin(time ...).
  3. Moon: a soft glow (a radial gradient) and a circle on top.
  4. Far flakes (z under 0.65): dim, drawn before the hills, so they look behind them.
  5. Back hill, then front hill.
  6. Near flakes (z over 0.65): bright, drawn last, so they pass in front.

Two things worth learning here:

  • drawFlakes builds one path for many circles and fills them once, instead of filling each flake on its own. That's much faster, which is why 500 flakes still run smoothly on a phone. The ctx.moveTo(f.x + r, f.y) before each arc stops the pen from drawing a line between circles.
  • drawHill walks across the screen in steps of 6 pixels, asks the hill function for the height at each step, connects the points, then closes the shape along the bottom and fills it.

Try: change 0.65 in both drawFlakes calls to 0.9. Almost all flakes go behind the hills.

Part 7: The loop and the controls

  • requestAnimationFrame(loop) calls loop before every screen refresh. Each time it works out dt, runs update, then draw.
  • Tapping: the pointerdown listener adds to gust. Which side you tap decides the direction. Math.max(...Math.min(...)) keeps it from getting out of control if you tap fast.
  • Sliders: KNOBS is a list of [name, label, min, max, step], and a loop builds one slider per line.

To add a slider, you do three things:

  1. Add a number to CFG.
  2. Add a line to KNOBS.
  3. Use it somewhere in the code.

Five experiments to learn from

  • 1. In makeFlake, change r: 1.2 + Math.random() * 2.2 to r: 3. Every flake is the same size.

  • 2. Change * 25 * u * f.z in the sway line to * 80 * u * f.z. Flakes swing wildly, like a snow globe.

  • 3. In drawFlakes, change 0.55 and 0.95 to 1 and 1. No more depth shading.

  • 4. Change groundY = H * 0.8 to H * 0.6. The hills rise and the sky shrinks.

  • 5. Replace ctx.arc(f.x, f.y, r, 0, 6.2832) in drawFlakes with ctx.rect(f.x, f.y, r * 2, r * 2). Square flakes, like pixel snow.