# Drawing Guide

An Epsil code block can draw: shapes, text, the graph of a function, pixels, and
pictures that move or respond to the pointer. This guide describes the drawing
functions. To run a block and to write to its console, see the
[Programming Guide](/programming-guide/en/). For plots that the reader can pan
and zoom, see
[Plot Functions in a Program](/programming-guide/en/#plot-functions-in-a-program).

## Contents

- [How a Drawing Works](#how-a-drawing-works)
- [Draw Shapes](#draw-shapes)
- [Colors](#colors)
- [Style and Move Shapes](#style-and-move-shapes)
- [Frame the Drawing With a Canvas](#frame-the-drawing-with-a-canvas)
- [Draw Graphs in a Drawing](#draw-graphs-in-a-drawing)
- [Work With Pixels](#work-with-pixels)
- [Animate a Drawing](#animate-a-drawing)
- [Respond to the Pointer and the Keyboard](#respond-to-the-pointer-and-the-keyboard)

## How a Drawing Works

The output of a code block has two parts: a picture and a console. The picture
is one drawing, or one plot.

**A drawing is made of shapes.** A shape is a value that a drawing can show: a
circle, a text, the graph of a function, an image. A function such as `circle`
makes a shape. It does not draw. The block shows the shapes that are the value
of its last statement:

```
let c = circle((0, 0), 1)
let d = segment((-1, 0), (1, 0))
[c, d]
```

A shape, or a list of shapes, is a drawing. In a list, a shape draws over the
shapes before it.

**A shape does not change.** Each method gives a new shape: `c.rotate(pi/6)` is
a rotated copy, and `c` stays as it was. In a type annotation, a shape is a
`CanvasShape`.

**`draw` replaces the picture.** `draw(x)` shows the drawing `x` in place of the
picture that the block shows. A block has no surface that keeps what was drawn
before. To animate, draw a new picture at each step (see
[Animate a Drawing](#animate-a-drawing)).

**Units.** A point is a pair `(x, y)` in drawing units: x goes right and y goes
up. The block chooses the scale so that the picture shows all the shapes, with a
small margin. A [canvas](#frame-the-drawing-with-a-canvas) sets the region
instead. The widths of lines are in screen pixels, so a line keeps its width
when the scale changes.

**Vector shapes and pixels.** Most shapes are vector graphics: they are sharp at
every size. A [heatmap](#draw-a-function-as-colors) and the
[image](#show-a-bitmap) of a bitmap are shapes that hold pixels.

**A plot is not a shape.** A plot is a picture of another kind: the reader pans
and zooms it, and it has its own axes. The block shows a plot in place of the
drawing, when `plot(…)` is the value of the program. A plot has no methods of a
shape, and `draw` does not take it: a plot cannot be in a list, in a group or on
a canvas. To draw the graph of a function among other shapes, use `graph`,
`curve` or `heatmap` (see
[Draw Graphs in a Drawing](#draw-graphs-in-a-drawing)).

## Draw Shapes

This program draws a circle, a diameter and a title:

```
[circle((0, 0), 1), segment((-1, 0), (1, 0)), label((0, 1.3), "unit circle")]
```

A point is a pair `(x, y)`, in parentheses: a list `[x, y]` is not a point, and
a function that takes a point reports a type error for it. Angles are in
radians, counterclockwise.

| Function                         | Makes                                                            |
| -------------------------------- | ---------------------------------------------------------------- |
| `point(p)`                       | a dot at `p`                                                     |
| `segment(p, q)`                  | a line segment from `p` to `q`                                   |
| `arrow(p, q)`                    | an arrow from `p` to `q`, with its head at `q`                   |
| `polyline([p1, p2, …])`          | an open line through the points                                  |
| `polygon([p1, p2, …])`           | a closed polygon through the points                              |
| `rect(corner, w, h)`             | a rectangle with its lower-left corner at `corner`               |
| `rect(corner, w, h, radius)`     | the same rectangle with rounded corners                          |
| `circle(c, r)`                   | a circle with center `c` and radius `r`                          |
| `ellipse(c, rx, ry)`             | an ellipse with horizontal radius `rx` and vertical `ry`         |
| `arc(c, r, start, end)`          | a circular arc from the angle `start` to the angle `end`         |
| `bezier(p0, p1, p2, p3)`         | a cubic Bézier curve from `p0` to `p3`                           |
| `label(p, text)`                 | a text centered on `p`; `$…$` in the text is math                |
| `path(d)`                        | a path in SVG path notation, such as `"M0,0 L1,0 L0,1 Z"`        |
| `svg(markup)`                    | an SVG fragment, placed with its lower-left corner at the origin |
| `graph(f, (x0, x1))`             | the graph of a function `x => y`                                 |
| `curve(f, (t0, t1))`             | a parametric curve `t => (x, y)`                                 |
| `heatmap(f, (x0, x1), (y0, y1))` | the values of a function `(x, y) => v`, as colors                |
| `image(b)`                       | the pixels of the bitmap `b`                                     |
| `group(a, b, …)`                 | one shape made of several                                        |

Each of these functions takes one more argument, which is optional and comes
last: a dictionary of options, as in `circle((0, 0), 1, {fill -> "gold"})`.
[Style and Move Shapes](#style-and-move-shapes) lists the options. For `graph`,
`curve` and `heatmap`, see
[Draw Graphs in a Drawing](#draw-graphs-in-a-drawing); for `image`, see
[Work With Pixels](#work-with-pixels).

To draw many shapes, compute the list. This program draws eight circles in eight
colors:

```
map(k => circle((k, 0), 0.4, {fill -> hsl(45*k, 0.7, 0.5)}), 1..8)
```

A path copied from an SVG file shows upside down, because the y axis of a
drawing points up; `.reflect("x")` turns it over.

## Colors

Where a function takes a color, give one of these:

- a color name, such as `"red"` or `"crimson"`, or a shade of a color scale,
  such as `"red-400"`; it gives the same color as `color("red")`;
- a hex string, such as `"#dc143c"`, or `"#dc143c80"` with an opacity;
- a color value, which one of these functions makes.

| Function            | Makes                                                               |
| ------------------- | ------------------------------------------------------------------- |
| `rgb(r, g, b)`      | a color from red, green and blue, each from 0 to 1                  |
| `rgb255(r, g, b)`   | the same from channels on the scale of 0 to 255                     |
| `hsl(h, s, l)`      | a color from a hue in degrees, a saturation and a lightness, 0 to 1 |
| `oklch(l, c, h)`    | a color from a lightness, a chroma and a hue of the OKLCH space     |
| `color(text)`       | the color value of a hex string: `color("#dc143c")`                 |
| `colormap(name, t)` | the color at the position `t`, from 0 to 1, of a palette            |

Each of the first four takes an optional last argument, the opacity `alpha`,
from 0 (transparent) to 1 (opaque): `rgb255(220, 20, 60, 0.5)`.

`rgb255(255, 128, 0)` is `rgb(1, 128/255, 0)`, the orange `"#ff8000"`. Do not
give numbers on the scale of 0 to 255 to `rgb`: `rgb(255, 128, 0)` is not
orange.

`color` reads a hex string or a color name. The names are those of CSS, such as
`"red"`, `"navy"` or `"crimson"`, but the colors are those of the palette of
Graph Paper, not the CSS values: `"red"` is `"#d7170b"`, not `"#ff0000"`. To get
the exact value of a CSS color, give its hex string.

`color` also reads a shade of a color scale: the name of a scale and a number
from 50, the lightest, to 950, the darkest, such as `"red-400"` or `"blue-700"`.
The scales are `pink`, `red`, `brown`, `orange`, `yellow`, `lime`, `green`,
`teal`, `cyan`, `blue`, `indigo` and `purple`.

After a name or a shade, `/` and a number give an opacity, from 0, transparent,
to 100, opaque: `"red-400/70"` or `"navy/50"`. The scale is 0 to 100, not 0 to
1: `"red-400/0.7"` is almost transparent.

### Read and Change a Color

A color value has these fields, whatever function made it:

| Field               | Value                                                     |
| ------------------- | --------------------------------------------------------- |
| `c.r`, `c.g`, `c.b` | the red, green and blue channels, from 0 to 1             |
| `c.l`, `c.c`, `c.h` | the lightness, the chroma and the hue, in the OKLCH space |
| `c.alpha`           | the opacity, from 0 to 1                                  |
| `c.hex`             | the hex string of the color                               |

The fields `l`, `c` and `h` are the three arguments of `oklch`. They are the
coordinates of the color in the OKLCH space, in which equal steps look equal to
the eye. OKLCH is not the older LCH space of CSS `lch()`, whose lightness goes
from 0 to 100.

| Field | Scale                                                                                  |
| ----- | -------------------------------------------------------------------------------------- |
| `c.l` | the lightness, from 0 (black) to 1 (white)                                             |
| `c.c` | the chroma: 0 for a gray, and at most about 0.32 for a color that `rgb` can make       |
| `c.h` | the hue, an angle from 0 to 360 degrees: red is near 30, green near 140, blue near 265 |

The hue of `hsl` is an angle on another scale: `hsl(0, 1, 0.5)` is red, and its
field `h` is about 29.

`c.update({…})` is a copy of `c` with the channels that it names replaced:
`c.update({l -> 0.8})` is a lighter color of the same hue, and
`c.update({h -> c.h + 180})` is the opposite hue.

A name or a hex string is a text, so it has no fields. Use `color` first:
`color("#dc143c").l`.

### Compare Two Colors

`c == d` is true when `c` and `d` are the same color, also when they were made
by two functions: `rgb(1, 0, 0) == hsl(0, 1, 0.5)` is true.

`c.matches(d, tol)` is true when each of the red, green and blue channels and
the opacity of `c` and `d` differ by at most `tol`. With `tol` at 0.02, two
colors match when they are within about 5 levels of 255 on each channel. Use it
to find the pixels that are near a color.

`colorDelta(c, d)` is the difference that the eye sees between two colors: 0 for
the same color, and about 1 between black and white.

## Style and Move Shapes

The last argument of each shape function is an optional dictionary of style
options: `circle((0, 0), 1, {fill -> "gold", color -> "black", width -> 2})` is
a gold disk with a black outline 2 pixels wide.

| Option           | Effect                                                                                                                                                          |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `color -> c`     | draws the line or the outline of the shape in the color `c`                                                                                                     |
| `width -> w`     | sets the width of the line or the outline, in pixels                                                                                                            |
| `fill -> c`      | fills the shape with the color `c`                                                                                                                              |
| `dash -> [4, 2]` | dashes the line or the outline: a list of dash and gap lengths in pixels, or one of the names `"solid"`, `"dashed"`, `"dotted"`, `"dot-dash"`, `"dot-dot-dash"` |
| `opacity -> a`   | sets the opacity, from 0 (invisible) to 1 (opaque)                                                                                                              |

These are the keys that an item of `plot` takes for its line. For a `point` and
a `label`, `color` is the color of the dot and of the text.

A `label` takes three more options:

| Option               | Effect                                                                          |
| -------------------- | ------------------------------------------------------------------------------- |
| `fontSize -> s`      | sets the size of the text in pixels; 16 without it                              |
| `fontFamily -> name` | sets the font: `"serif"`, `"sans-serif"` or `"monospace"`                       |
| `background -> c`    | fills the box of the text, with a small margin, in the color `c`, as for `fill` |

For example,
`label((0, 2), "Results", {fontSize -> 24, fontFamily -> "serif", color -> "navy"})`
is a large title. A background keeps a label readable over lines:
`label((1, 1), "42", {background -> "white"})` hides the lines under its text.

`c.update({fill -> "blue"})` is a copy of the shape `c` with the options that it
names replaced; the other options stay. `nothing` removes an option:
`c.update({fill -> nothing})`. An unknown option, or a value of the wrong kind,
gives a warning under the drawing, and the other options apply.

A shape has no option for its position. To move it, turn it or change its size,
use a method. Each method returns a changed copy, so you can chain them:
`rect((0, 0), 2, 1).rotate(pi/6).translate((1, 0))`. To write a chain over
several lines, start each new line with the dot.

| Method                           | Effect                                                           |
| -------------------------------- | ---------------------------------------------------------------- |
| `.update(options)`               | replaces the style options that `options` names                  |
| `.translate((dx, dy))`           | moves the shape                                                  |
| `.rotate(a)`, `.rotate(a, p)`    | rotates it about its center, or about the point `p`              |
| `.scale(k)`, `.scale((kx, ky))`  | scales it about its center                                       |
| `.scaleAbout(k, p)`              | scales it about the point `p`                                    |
| `.reflect("x")`, `.reflect("y")` | turns it upside down, or mirrors it left to right                |
| `.skew(ax, ay)`                  | skews it about its center                                        |
| `.bounds()`                      | the box of the shape, `((x0, y0), (x1, y1))`                     |
| `.center()`                      | the center of that box                                           |
| `.anchor(name)`                  | a point of the box: `"n"`, `"ne"`, `"e"`, … `"nw"` or `"center"` |
| `.on(name, handler)`             | handles an event (see the last section)                          |

To style or move several shapes together, make a group of them. A style set on a
group applies to each part that does not set its own, so
`group(circle((0, 0), 1), circle((1, 0), 1), {color -> "navy", width -> 3})`
outlines both circles: a last argument of `group` that is a dictionary is its
options, not a part. A method of a group applies to the group as one shape.

Use the queries to place one shape relative to another: with
`r = rect((0, 0), 4, 2)`, `label(r.anchor("n"), "top")` puts a label at the
middle of the top edge.

## Frame the Drawing With a Canvas

Without a canvas, the drawing fits its shapes. To choose the region that the
drawing shows, or to add a grid and axes, put the shapes on a canvas:

```
canvas([graph(x => sin(x), (-pi, pi))], {grid -> true, axes -> true, bounds -> ((-4, -1.5), (4, 1.5))})
```

`canvas(shapes, options)` takes a shape or a list of shapes, and these options:

| Option                           | Effect                                           |
| -------------------------------- | ------------------------------------------------ |
| `bounds -> ((x0, y0), (x1, y1))` | the region shown; the shapes are clipped to it   |
| `aspect -> r`                    | the height of the drawing is `r` times its width |
| `grid -> true`                   | draws a grid                                     |
| `axes -> true`                   | draws the two axes, with ticks and numbers       |
| `background -> c`                | fills the region with the color `c`              |

Without `aspect`, one unit has the same length on both axes.

**A drawing has one canvas.** The canvas is the frame of the whole drawing, so
it is the value of the program, or the argument of `draw`. A canvas in another
canvas, in a group, or in a list with other shapes does nothing more than a
group: the drawing shows its shapes, ignores its options, and gives a warning.
To make one shape of several shapes on a canvas, use `group`:

```
let wheel = group(circle((0, 0), 1), segment((-1, 0), (1, 0)), segment((0, -1), (0, 1)))
canvas([wheel, wheel.rotate(pi/4).translate((3, 0))], {grid -> true})
```

`.update(options)` on a canvas changes its options. The option `content`
replaces all the shapes of the canvas and keeps the rest:
`court.update({content -> [ball, paddle]})` is the same canvas with two new
shapes.

## Draw Graphs in a Drawing

Three functions draw a function among the other shapes of a drawing:

| Function                         | Makes                                                             |
| -------------------------------- | ----------------------------------------------------------------- |
| `graph(f, (x0, x1))`             | the graph of `x => y` for `x` from `x0` to `x1`                   |
| `curve(f, (t0, t1))`             | the parametric curve `t => (x, y)` for `t` from `t0` to `t1`      |
| `heatmap(f, (x0, x1), (y0, y1))` | the values of `(x, y) => v` as colors, over the ranges of x and y |

They make shapes, so they can be in a list, in a group or on a canvas, with
other shapes on top of them:

```
canvas([
  heatmap((x, y) => sin(x*y), (-3, 3), (-3, 3)),
  graph(x => 1/x, (0.3, 3), {color -> "white"}),
  curve(t => (2*cos(t), 2*sin(t)), (0, 2*pi), {color -> "white", dash -> [4, 2]})
], {axes -> true})
```

A range is a pair, `(x0, x1)`. You can leave a range out: it is then
`(-10, 10)`, so `graph(x => x^2)` draws the function for `x` from -10 to 10, and
`heatmap(f)` covers -10 to 10 on both axes.

`graph` and `curve` leave a gap where the function has no real value, or jumps.
They take the style options of a line: `color`, `width`, `dash` and `opacity`.

These shapes do not respond to the reader. For a plot that the reader pans and
zooms, with axes and a legend, use
[`plot`](/programming-guide/en/#plot-functions-in-a-program).

### Draw a Function as Colors

`heatmap` computes a function of two variables at the center of each pixel of a
rectangle. Its second argument is the range of x, and its third argument is the
range of y. Give both ranges or none:

```
heatmap((x, y) => sin(x*y), (-3, 3), (-3, 3), {colormap -> "magma"})
```

A real value goes through the colormap, a color value is drawn as it is, and a
boolean draws as 0 or 1. The source can also be a matrix, a list of rows with
row 1 at the top: the rows then cover the two ranges.

| Option                 | Effect                                         | Default                 |
| ---------------------- | ---------------------------------------------- | ----------------------- |
| `resolution -> (w, h)` | the number of pixels                           | 256 on the longer side  |
| `colormap -> name`     | the palette of real values                     | `"viridis"`             |
| `range -> (lo, hi)`    | the values at the two ends of the colormap     | the range of the values |
| `smooth -> false`      | draws sharp cells in place of a smooth picture | smooth for a function   |
| `opacity -> a`         | sets the opacity, from 0 to 1                  | 1                       |

The pixels of a heatmap are computed once, when the program runs, and the
program cannot read them. For pixels that the program reads and changes, use a
[bitmap](#work-with-pixels).

### Place a Graph

A graph, a curve and a heatmap have no option for their position. Each one draws
at the coordinates of its function: the point `(x, f(x))` of
`graph(f, (x0, x1))` is at `(x, f(x))` in the drawing, and a heatmap covers the
rectangle of its two ranges. To put one in another place, or to change its size,
use the methods of a shape: `.translate((dx, dy))` moves it, and `.scale(k)`
changes its size about the center of its box.

This program draws four graphs, each in a frame, in two rows:

```
function panel(f, dx, dy) {
  group(rect((-pi, -1), 2*pi, 2, {color -> "gray"}), graph(f, (-pi, pi), {color -> "crimson"}))
    .translate((dx, dy))
}
[panel(sin, 0, 0), panel(cos, 7, 0), panel(x => sin(2*x), 0, -3), panel(x => cos(2*x), 7, -3)]
```

`group` makes one shape of the frame and the graph, and `translate` moves both.
The axes of a canvas show drawing units, so they do not give the values of a
graph that was moved or scaled.

## Work With Pixels

A bitmap is a grid of pixels that a program makes, reads, changes and shows. Use
it for a simulation, a game, or an image filter. Each pixel is a
[color](#colors).

```
let picture = bitmap(320, 200, "navy")
picture.set(10, 20, rgb255(240, 180, 40))
image(picture)
```

A bitmap is an array of pixels: it has no position, and the block does not show
it. To put the pixels in the drawing, make an image: `image(b)` is a shape that
refers to the pixels of `b` and has a position in the drawing.

### Make a Bitmap

| Call              | Result                                                   |
| ----------------- | -------------------------------------------------------- |
| `bitmap(w, h)`    | a bitmap of `w × h` transparent pixels                   |
| `bitmap(w, h, c)` | a bitmap in which every pixel has the color `c`          |
| `bitmap(rows)`    | a bitmap from a list of rows of colors; row 1 is the top |
| `b.copy()`        | a new bitmap with the same pixels                        |

`b.width` and `b.height` are the size of `b` in pixels. A side has 1 to 2048
pixels, and a bitmap has at most 1,048,576 pixels. The bitmaps of a notebook
take at most 64 MiB together.

A bitmap changes in place: after `let b = a`, a change through `a` shows through
`b`. Use `copy()` for an independent bitmap.

### Read and Write One Pixel

The pixel `(0, 0)` is at the top left: `x` counts to the right and `y` counts
down, both from 0. A coordinate is an integer; use `floor(x)` for another
number.

| Method           | Effect                                    |
| ---------------- | ----------------------------------------- |
| `b.get(x, y)`    | the color of the pixel at `(x, y)`        |
| `b.set(x, y, c)` | gives the pixel at `(x, y)` the color `c` |

A read outside the bitmap gives a transparent color, and a write outside it does
nothing. `set` takes a color value only; the other methods of a bitmap that take
a color also take a color name or a hex string.

A bitmap keeps 8 bits for each channel of a pixel. A color that you write is
rounded to the nearest of the 256 levels, so a pixel can differ a little from
the color that you wrote. A color from a name, from a hex string, from `rgb255`
with whole numbers, or from another pixel is kept exactly, and `==` finds it
again.

### Change Every Pixel

| Method                | Effect                                                             |
| --------------------- | ------------------------------------------------------------------ |
| `b.fill(c)`           | gives every pixel the color `c`                                    |
| `b.fill((x, y) => c)` | gives each pixel the color that the function computes for `(x, y)` |
| `b.map(c => d)`       | replaces the color `c` of each pixel by the color `d`              |

Use `fill` with a function when the color depends on the position, and `map`
when it depends only on the color of the pixel:

```
picture.fill((x, y) => hsl(x, 1, y / 400))
picture.map(c => rgb(1 - c.r, 1 - c.g, 1 - c.b, c.alpha))
picture.map(c => c.update({h -> c.h + 30}))
```

The second line inverts the picture. The third line turns each hue by 30
degrees.

While `fill` or `map` runs, every `b.get` reads the pixels of before the call.
So the function of `fill` can read the neighbors of a pixel: a blur, or one step
of a simulation, is one call.

### Draw Shapes and Copies in a Bitmap

| Method                          | Effect                                                         |
| ------------------------------- | -------------------------------------------------------------- |
| `b.fillRect((x, y), (w, h), c)` | colors the `w × h` pixels whose top-left pixel is `(x, y)`     |
| `b.line((x0, y0), (x1, y1), c)` | colors the pixels of the segment between two pixels            |
| `b.blit(src, (x, y))`           | copies the pixels of `src` with its top-left pixel at `(x, y)` |

A rectangle, a line or a copy that is partly outside the bitmap changes only the
pixels inside it. A third argument of `blit` is a dictionary of options:
`blend -> true` draws each pixel of `src` over the pixel below with its opacity.

To copy a part of a bitmap, make a sprite. `sprite(src, (x, y), (w, h))` is a
view of the `w × h` pixels of the bitmap `src` whose top-left pixel is `(x, y)`.
A sprite holds no pixels: it reads the pixels of `src` when a function uses it,
so it shows a later change of `src`. Give a sprite where a function reads a
bitmap: as the source of `blit`, or as the argument of `image`. A sprite also
has `width`, `height` and `get`. It has no method that writes.

This program cuts four pictures of 16 × 16 pixels from one row of a bitmap
`sheet` and copies one of them to the bitmap `page`:

```
let frames = map(k => sprite(sheet, (16*k, 0), (16, 16)), 0..3)
page.blit(frames[2], (40, 20), {blend -> true})
```

### Show a Bitmap

| Call                        | Result                                                  |
| --------------------------- | ------------------------------------------------------- |
| `image(b)`                  | a shape that shows `b`, one drawing unit for each pixel |
| `image(b, bounds)`          | a shape that shows `b` in the rectangle `bounds`        |
| `image(b, options)`         | `image(b)` with options                                 |
| `image(b, bounds, options)` | `image(b, bounds)` with options                         |

`image(b)` puts the lower-left corner of the bitmap at the origin, and `bounds`
is a rectangle `((x0, y0), (x1, y1))`. The options are `smooth -> true`, which
blends neighboring pixels (without it each pixel is a sharp square), and
`opacity -> a`.

An image is a shape like the others: it can be in a list, in a group or on a
canvas, it takes the methods of a shape, and other shapes draw on top of it. It
refers to the bitmap and does not copy it: it shows the pixels that the bitmap
has when the picture is drawn.

### Make a Pixel Function Fast

The function of `fill` or `map` runs once for each pixel, so the block compiles
it. When it cannot compile it, the console says why, and the call is much
slower: on 320 × 200 pixels, a function that the block cannot compile can take
more than a minute in place of less than 0.1 second.

- The function must only compute a color. It cannot print, draw, or change a
  variable or a bitmap.
- Return a color value, not a text: `color("red")` or `rgb255(215, 23, 11)`, not
  `"red"`. Make the bitmaps and the colors that it uses before the call.
- The pixel function and the functions that it calls need no types on their
  parameters.
- In an animation, the pixel function can read the argument of the timer
  function, a variable of the timer function or a variable of the block (see
  [Animate a Drawing](#animate-a-drawing)). When the value that changes at each
  tick is a number, a true/false value, a color, or a list of numbers or of
  points, the block compiles the pixel function once.

The exception: when the pixel function, or a function that it calls, gives
`get` a position computed with `%` by a value that is not a constant, give its
parameters the type `integer`, as in
`function at(x: integer, y: integer) -> integer { … }`.

A function that reads the fields `r`, `g`, `b` and `alpha` is fast: an inversion
of 1024 × 1024 pixels takes about 4 ms. A function that reads `l`, `c` or `h`,
or changes them with `update`, converts each pixel to OKLCH and back: a turn of
the hue of the same pixels takes about 180 ms.

### Example: The Game of Life

This board wraps at its sides. Each step is one `fill`, because the function
reads the pixels of the generation before:

```
const side = 128
let live = color("white")
let dead = color("black")
let board = bitmap(side, side, dead)
board.set(1, 0, live); board.set(2, 1, live)
board.set(0, 2, live); board.set(1, 2, live); board.set(2, 2, live)

function at(x: integer, y: integer) -> integer {
  if board.get((x + side) % side, (y + side) % side) == live { 1 } else { 0 }
}
function next(x: integer, y: integer) -> color {
  let k = at(x - 1, y - 1) + at(x, y - 1) + at(x + 1, y - 1) +
    at(x - 1, y) + at(x + 1, y) +
    at(x - 1, y + 1) + at(x, y + 1) + at(x + 1, y + 1)
  if k == 3 || (k == 2 && at(x, y) == 1) { live } else { dead }
}

draw(image(board))
timer(50, t => do {
  board.fill(next)
  draw(image(board))
})
```

## Animate a Drawing

To animate, call a function on a timer and draw a new picture at each tick.
`timer(ms, callback)` calls `callback(t)` every `ms` milliseconds after the run
ends, where `t` is the time in milliseconds since the timer started:

```
timer(16, t => draw(circle((cos(t / 1000), sin(t / 1000)), 0.1, {fill -> "crimson"})))
```

`timer` returns the timer, and the method `stop()` of the timer ends it. This
animation stops after 5 seconds:

```
let clock = timer(16, t => do {
  draw(circle((cos(t / 1000), sin(t / 1000)), 0.1, {fill -> "crimson"}))
  if t > 5000 { clock.stop() }
})
```

The timers also end when you run the block again, choose **Stop**, or edit the
block. A block has at most 16 timers.

In a run, `draw` replaces the value of the program as the drawing of the block.
`draw([])` shows an empty picture.

A function defined with `function` that changes a variable of the block must
declare the `scope` effect: `function step(t) scope { n = n + 1 }`.

To animate a bitmap, change it in the timer and draw its image again, as the
Game of Life does. When the colors depend on the time, keep the time in a
variable of the block:

```
let picture = bitmap(320, 200)
let turn = 0
function shade(x: integer, y: integer) -> color { hsl(x + turn, 1, y / 400) }

timer(16, t => do {
  turn = t / 10
  picture.fill(shade)
  draw(image(picture))
})
```

The timer sets `turn`, and `shade` reads it. The block compiles `shade` once.

## Respond to the Pointer and the Keyboard

`s.on(name, handler)` is a copy of the shape `s` that calls `handler` at a
pointer event: `"click"`, `"pointerdown"`, `"pointerup"`, `"pointermove"`,
`"pointerenter"` or `"pointerleave"`. On a canvas, the handler is for the whole
drawing. The handler can change the variables of the block and call `draw` with
a new picture. This circle grows at each click:

```
let r = 1
function scene() {
  canvas([circle((0, 0), r, {fill -> "tomato"}).on("click", e => do { r = r + 0.5; draw(scene()) })], {bounds -> ((-5, -5), (5, 5))})
}
scene()
```

The handler gets one argument, a dictionary:

| Key                          | Value                                                           |
| ---------------------------- | --------------------------------------------------------------- |
| `e.x`, `e.y`                 | the point of the pointer, in drawing units                      |
| `e.pixel`                    | on an image: the pixel `(x, y)` of its bitmap under the pointer |
| `e.type`                     | the event name                                                  |
| `e.shift`, `e.alt`, `e.meta` | the modifier keys                                               |

An event goes to the shape under the pointer, then to each group that holds it,
then to the canvas. During a drag of a shape that handles `"pointermove"`, the
moves outside the shape still reach it.

To handle several events, chain the calls:
`s.on("pointerdown", press).on("pointerup", release)`. A shape has one handler
per event name: a second `.on` with the same name replaces it.

### Stop a Handler

`s.stop()` ends the handlers of the shape `s`. The shape still shows, and it no
longer responds. This circle prints a line at each click, for 5 seconds:

```
let target = circle((0, 0), 1, {fill -> "tomato"}).on("click", e => print("hit"))
draw(target)
timer(5000, t => target.stop())
```

`on` and `stop` are the two functions of the protocol `EventHandler`. Every
shape conforms to it: the shape that `.on` returns is the value that you keep to
stop its handlers. `stop()` of a timer ends the timer in the same way.

### Handle the Pointer Anywhere

Put the handlers on the canvas once and draw new shapes on it with `update`. The
handlers stay, so a drag continues when the shape under the pointer disappears:

```
let x = 0
let redraw = () => draw(court.update({content -> circle((x, 0), 1)}))
let court = canvas([], {bounds -> ((-5, -5), (5, 5))}).on("pointermove", e => do { x = e.x; redraw() })
redraw()
```

### Example: Paint

`e.pixel` gives the pixel under the pointer, so a handler on an image can paint
in its bitmap:

```
let page = bitmap(400, 300, "white")
let ink = "navy"
let down = false
let from = (0, 0)
let view = () => image(page)
  .on("pointerdown", e => do { down = true; from = e.pixel })
  .on("pointerup", e => do { down = false })
  .on("pointermove", e => do {
    if down {
      page.line(from, e.pixel, ink)
      from = e.pixel
      draw(view())
    }
  })
draw(view())
```

For a handler that is not on the image, `b.pixelAt((e.x, e.y))` gives the pixel
of `b` under a drawing point, for `image(b)`; `b.pixelAt(q, bounds)` for
`image(b, bounds)`.

### The Keyboard

A canvas that is the value of the program can also handle `"keydown"` and
`"keyup"`. Click the drawing or Tab to it to give it focus. Read `e.code` for
physical keys such as `"ArrowUp"` and `e.key` for the character typed. When
focus leaves the drawing, the handler receives a `keyup` for each key still
held.

### When the Handlers End

The handlers end when you run the block again, choose **Stop**, or edit the
block. A drawing restored when the notebook opens, and an exported drawing, do
not respond: run the block first.
