> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# Draw on a canvas

Draw charts, signatures and edited photos with a [`<canvas>`](/api/elements/canvas.md) and its 2D context, as on the web. Chart and image libraries that draw with [`getContext('2d')`](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D) work too.


## Where it works

Lynx has no canvas of its own: this one is AngularLynx's. So it draws only where AngularLynx ships its native code:

- **Your iOS and Android apps**, built with [`ng build --platform ios|android`](/guide/building-for-production.md)
- **The [web preview](/guide/glossary.md#web-preview)**, where it's the browser's own HTML `<canvas>`

[Lynx Explorer](/guide/glossary.md#lynx-explorer), and native apps that embed Lynx themselves, don't have the canvas element. There the canvas is an empty view, and `getContext()` returns `null`. [Platform support](/api/elements/canvas.md#platform-support) shows what draws it on each platform.

## Draw in 2D

Give the canvas a size with CSS. Once it's laid out, size its drawing buffer to the screen's pixels, then draw:

```typescript title="src/app/chart.ts"
import {
  afterNextRender,
  Component,
  type ElementRef,
  viewChild,
} from '@angular/core';
import { LYNX_ELEMENTS, type LynxCanvasElement } from '@blotch/angular-lynx';

@Component({
  selector: 'app-chart',
  imports: [LYNX_ELEMENTS],
  template: `<canvas #canvas class="h-[200px] w-full"></canvas>`,
})
export class Chart {
  readonly canvas = viewChild.required<ElementRef<LynxCanvasElement>>('canvas');

  constructor() {
    afterNextRender(() => {
      const canvas = this.canvas()
        .nativeElement as unknown as HTMLCanvasElement;
      const context = canvas.getContext('2d')!;
      new ResizeObserver(([entry]) => {
        const { width, height } = entry.contentRect;
        // Setting the size clears the canvas and resets its state.
        canvas.width = width * devicePixelRatio;
        canvas.height = height * devicePixelRatio;
        context.scale(devicePixelRatio, devicePixelRatio);
        const gradient = context.createLinearGradient(0, 0, 0, height);
        gradient.addColorStop(0, '#818cf8');
        gradient.addColorStop(1, '#4338ca');
        context.fillStyle = gradient;
        context.beginPath();
        context.roundRect(20, 40, 60, height - 60, [8, 8, 0, 0]);
        context.fill();
        context.font = '14px sans-serif';
        context.fillText('Sales', 20, 24);
      }).observe(canvas);
    });
  }
}
```

- **The CSS size** is how big the canvas is shown.
- **`width` and `height`** are its **drawing buffer**: the pixels you draw into, 300 by 150 to start. Multiply by `devicePixelRatio` so it's sharp.
- **`ResizeObserver`** reports the canvas's size as it changes. `clientWidth`, `clientHeight` and `getBoundingClientRect()` answer from its last layout.

## What you can draw

The whole [CanvasRenderingContext2D](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D) is there:

- **Shapes:** paths, `Path2D` (with SVG path data), rectangles, arcs and rounded rectangles
- **Transforms and clipping**
- **Lines:** widths, joins and dashes
- **Fills:** colors, patterns, and linear, radial and conic gradients
- **Effects:** shadows, `globalAlpha` and every `globalCompositeOperation`
- **Text:** `font`, `textAlign`, `textBaseline`, `direction`, `letterSpacing` and `measureText()`
- **Images:** `drawImage()` of images, `ImageBitmap`s and other canvases
- **Pixels:** `getImageData()`, `putImageData()` and `isPointInPath()`

A few parts behave differently, such as `filter` and some text properties. See [What's different from the web](/api/elements/canvas.md#whats-different-from-the-web).

## Draw off screen

Canvases the page doesn't show work too. `document.createElement('canvas')` and `new OffscreenCanvas(width, height)` have a 2D context. You can:

- draw one on another canvas
- make it a pattern
- upload it as a WebGL texture (three.js's `CanvasTexture`)
- save it as an image

That's how three.js apps draw text labels, and how image libraries resize a photo.

## Handle touches

Pointer events (`pointerdown`, `pointermove`, `pointerup` and the rest) work, from the finger's touches. They work on every element, not only a canvas: see [Element events](/api/angular-lynx/element-events.md).

## What the build includes

The build leaves out canvas code your app never uses. It looks through every module of your app and its libraries for the names below. An app that never draws doesn't load any of it.

| Code                                         | Included when a module                                                                                     | Size of the [main-thread](/guide/glossary.md#main-thread) script |
| -------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
| The `<canvas>` element and its image classes | Names `'canvas'` or `'bitmaprenderer'` in quotes or an image class, or passes `'img'` to `createElement()` | About 21 kB                                                      |
| The 2D context and its classes               | Names `'2d'` in quotes, or one of its classes                                                              | About 40 kB                                                      |
| The WebGL2 context                           | Names `'webgl2'`                                                                                           | About 37 kB                                                      |

Your code usually names them already:

- A template's `<canvas>` and `document.createElement('canvas')` name `'canvas'`.
- `getContext('2d')`, and chart and image libraries, name `'2d'`.
- three.js and `getContext('webgl2')` name `'webgl2'`.

**The image classes** are `OffscreenCanvas`, `ImageData`, `Image`, `HTMLImageElement`, `ImageBitmap`, `ImageBitmapRenderingContext` and `createImageBitmap()`. The same code also makes `document.createElement('canvas')` and `('img')` work. **The 2D context's classes** are `Path2D`, `CanvasRenderingContext2D`, `CanvasGradient`, `CanvasPattern` and `TextMetrics`. These classes are globals only when their code is built in.

### Names built at runtime

The build can't see a name your code puts together while it runs. Unless another module names it:

- **A `<canvas>` from a tag built at runtime** is a plain element, with a console warning.
- **A context name built at runtime** gets `null` and a console warning, on iOS and Android.

Write the tag out in a template and the context name in full. Or call one of these from `@blotch/angular-lynx` first:

- `ɵenableCanvas()`, before you make the canvas
- `ɵenableCanvas2D()`, before `getContext('2d')`
- `ɵenableWebGL2()`, before `getContext('webgl2')`

The web preview's canvas is the browser's, which has its own contexts.

## The canvas in the native app

`ng build --platform ios|android` builds the native code behind `<canvas>` into the app only when a module of your app or its libraries can draw. A module can draw when it names one of these:

- `'webgl2'`, or the 2D context, as above
- `'canvas'` or `'bitmaprenderer'` in quotes, as a template's `<canvas>` and `document.createElement('canvas')` do, or `'img'` as `createElement()`'s tag
- `OffscreenCanvas`, `HTMLCanvasElement`, `Image`, `HTMLImageElement`, `ImageBitmap`, `createImageBitmap` or `ImageBitmapRenderingContext`

**An app that never draws** leaves out the canvas, its WebGL and 2D contexts, and `<video>`'s readable frames. That's about 176 kB of the iOS app. It also leaves out **ANGLE**, the library iOS draws WebGL with: about 6 MB.

**An app that draws only in 2D**, such as a chart or a signature pad, keeps the canvas. It leaves out the WebGL context and ANGLE. The 2D context draws with Core Graphics on iOS and `android.graphics.Canvas` on Android, and needs neither.

**The WebGL context** comes only when a module names `'webgl2'` (anywhere, even in a comment), `WebGL2RenderingContext` or `ɵenableWebGL2`.

Without that code, a `<canvas>` shows nothing and `getContext()` returns `null`. If your app builds every canvas name at runtime, call `ɵenableCanvas()`, `ɵenableCanvas2D()` or `ɵenableWebGL2()`. Each one brings the native code too. `ɵenableWebGL2()` brings the WebGL context and ANGLE as well.

These apps always keep all of it:

- **The development app** from `ng serve --platform`, since you can add a canvas while it runs
- **An ejected project** (`ng generate @blotch/angular-lynx:eject`), since it's yours to change
- **An app built with Rsbuild's persistent cache** (`performance.buildCache`), whose cached modules the build doesn't read again

## Next steps

- [Draw in 3D](/guide/canvas/3d.md): three.js, angular-three, textures and models
- [Images, videos and saving](/guide/canvas/media.md): crop bitmaps, draw a video's frame, export a JPEG
- [`<canvas>`](/api/elements/canvas.md): attributes, methods, events and web differences
