Task 3 of 4

Plot a Function

How do you plot y = f(x) when no thread can draw a line? Flip the question: every pixel decides for itself whether it lies on the curve. Thread (x, y) evaluates the function at its own x, measures the vertical distance to that height, and paints amber if the distance is under 2 pixels — background otherwise.

This per-pixel "how far am I from the shape?" question is one of the great tricks of computer graphics. Today it draws a sine wave; the same idea, pushed further, draws the fractals of Escape-Time Fractals and the ray-marched scenes of Ray-Marched Metaballs.

no thread draws the line — each pixel just answers: am i near it?
Goal: plot one full period of y = 64 + 40 · sin(2πx / 128) as a thin amber curve on the dark background.

Requirements

Hint 1 — one line changes

The distance test and both colors are already written. Only curveY is wrong: it's a constant, so you get a flat line instead of a wave.

Hint 2 — the curve
const curveY = 64 + 40 * Math.sin(x * 2 * Math.PI / 128);

Math.sin and Math.PI both work inside kernels.

Same idea elsewhere

Distance-to-shape rendering is how GPUs draw crisp text and vector art at any zoom (signed distance fields), and it's the engine behind every Shadertoy graph you've seen: a WGSL or Metal fragment shader evaluating f(x) per fragment, exactly as here.

All tasks in Pixels from Scratch

  1. Paint with Coordinates
  2. Checkerboard Logic
  3. Plot a Function
  4. Ripples: Think in Polar

This page is an interactive exercise — the editor, the GPU runner and your saved progress need JavaScript. The text above is the full brief.