Build a drawing game · Exercise 01

Build a canvas

Start a React app on a Worker and build a canvas that works with a mouse, a finger, or a pen.

Build a canvas

Every round of your game starts with a blank canvas. In this exercise you’ll start the app and build that canvas: something you can draw on with a mouse, a finger, or a pen, plus a preview of exactly what the model will see when it guesses.

What you’ll build

A React app on a Worker, made with cf init, with a drawing canvas, a Clear button, and a small preview of your drawing at the size you’ll send to the model.

One Worker, two halves

Your game is one Worker with two halves. The page, written in React, runs in the player’s browser: that’s where the drawing happens. The Worker runs on Cloudflare: in the next exercise it gets an endpoint that sends each drawing to the model. Vite builds the page into static files, and Cloudflare serves those files before your Worker code runs, so the Worker only handles what isn’t a file, like /api/guess.

my-game/
├── index.html            the page's shell
├── app/                  runs in the browser
│   ├── main.tsx
│   └── App.tsx
├── src/index.ts          runs on Cloudflare
├── cloudflare.config.ts
└── vite.config.ts

Drawing with pointer events

Pointer events cover a mouse, a finger, and a pen with the same code, so you don’t need separate touch handling:

app/App.tsxconst onPointerDown = (e: React.PointerEvent<HTMLCanvasElement>) => {
  e.currentTarget.setPointerCapture(e.pointerId); // keep drawing if the pointer leaves the canvas
  const ctx = e.currentTarget.getContext("2d")!;
  ctx.beginPath();
  ctx.moveTo(...toCanvas(e));
  drawing.current = true;
};

const onPointerMove = (e: React.PointerEvent<HTMLCanvasElement>) => {
  if (!drawing.current) return;
  const ctx = e.currentTarget.getContext("2d")!;
  ctx.lineTo(...toCanvas(e));
  ctx.stroke();
};

Two details matter on a phone. The canvas has a fixed size in pixels but is stretched to fit the screen with CSS, so each pointer position has to be converted from screen pixels to canvas pixels (that’s toCanvas). And without touch-action: none on the canvas, dragging a finger scrolls the page instead of drawing.

What the model will see

The model doesn’t need your full-size canvas. Before sending a drawing, your page shrinks it to 256×256 pixels and turns it into a PNG. The preview shows that image, so what you see is what the model gets. The canvas is filled white first, because a PNG’s empty pixels are transparent, not white. When we sent black lines on a transparent background, the model answered exactly as it did for an empty canvas: it saw nothing at all.

Prerequisites

Your agent can help you with these.