Skip to main content
The Canvas class is a static abstraction over three rendering backends. Rather than calling the browser Canvas API or CanvasKit directly, all rendering in GeoPackage JS goes through Canvas, which delegates to whichever adapter is registered for the current runtime environment. GeoPackageManager.open() and GeoPackageManager.create() call Canvas.initializeAdapter() automatically, so you normally do not need to call it yourself. You only need to interact with Canvas directly when:
  • Running in Node.js and freeing memory (disposeCanvas, disposeImage).
  • Overriding the default WASM file locations.
  • Registering a custom adapter.

Adapters

The correct adapter is selected automatically based on the detected runtime environment.
AdapterEnvironmentBackend
HtmlCanvasAdapterBrowser (main thread)Standard HTMLCanvasElement / Canvas 2D API
CanvasKitCanvasAdapterNode.jsCanvasKit WebAssembly (Skia)
OffscreenCanvasAdapterWeb WorkerOffscreenCanvas + createImageBitmap
The selection happens in Context.setupDefaultContext(), which is called as part of GeoPackageManager.open() and GeoPackageManager.create().

WASM file location

Node.js — CanvasKit WASM

By default, CanvasKitCanvasAdapter looks for canvaskit.wasm relative to the installed package. If you bundle the library or move the WASM file, call setCanvasKitWasmLocateFile before opening any GeoPackage:
import { CanvasKitCanvasAdapter } from '@ngageoint/geopackage';

CanvasKitCanvasAdapter.setCanvasKitWasmLocateFile((filename) =>
  `/custom/path/to/wasm/${filename}`
);
static setCanvasKitWasmLocateFile(
  locateFile: (filename: string) => string
): void
locateFile
(filename: string) => string
required
A function that receives the WASM filename (e.g. "canvaskit.wasm") and returns the full path or URL where it can be found.

Browser — sql.js WASM

The SqljsAdapter (used for the underlying SQLite layer in the browser) also requires a WASM file. Configure its location with setSqljsWasmLocateFile:
import { SqljsAdapter } from '@ngageoint/geopackage';

SqljsAdapter.setSqljsWasmLocateFile((filename) =>
  `https://cdn.example.com/wasm/${filename}`
);
static setSqljsWasmLocateFile(
  locateFile: (filename: string) => string
): void
locateFile
(filename: string) => string
required
A function that receives the WASM filename (e.g. "sql-wasm.wasm") and returns the URL where it can be fetched.
You must call setSqljsWasmLocateFile before calling GeoPackageManager.open() or GeoPackageManager.create(), otherwise the browser may fail to load the WASM bundle from the wrong path.

Static methods

initializeAdapter()

Initializes the registered canvas adapter. This is called automatically by GeoPackageManager.open() and GeoPackageManager.create(); you only need to call it manually if you are constructing a canvas outside of those entry points.
static async initializeAdapter(): Promise<void>
Throws if no adapter has been registered or if the adapter’s own initialization fails.

create()

Creates a new canvas of the given dimensions using the active adapter.
static create(width: number, height: number): HTMLCanvasElement
width
number
required
Width of the canvas in pixels.
height
number
required
Height of the canvas in pixels.
Returns an adapter-specific canvas object — an HTMLCanvasElement in the browser, an EmulatedCanvas2D in Node.js (CanvasKit), or an OffscreenCanvas in a Web Worker.
import { Canvas } from '@ngageoint/geopackage';

const canvas = Canvas.create(256, 256);
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#ff0000';
ctx.fillRect(0, 0, 256, 256);

disposeCanvas()

Releases resources held by a canvas created with Canvas.create(). In Node.js (CanvasKit), failing to call this leaks native WASM memory. In the browser the call is a no-op, but it is good practice to call it unconditionally.
static disposeCanvas(canvas: any): void
canvas
any
required
The canvas object previously returned by Canvas.create().
In Node.js, every canvas created with Canvas.create() must be disposed with Canvas.disposeCanvas() when you are finished with it. CanvasKit allocates memory outside the V8 heap, so the garbage collector cannot reclaim it automatically.
const canvas = Canvas.create(512, 512);
try {
  // ... draw on canvas ...
} finally {
  Canvas.disposeCanvas(canvas);
}

disposeImage()

Releases resources held by a GeoPackageImage. In Node.js (CanvasKit), failing to call this leaks native WASM memory.
static disposeImage(image: GeoPackageImage): void
image
GeoPackageImage
required
The image to dispose. The image must not be used after this call.
In Node.js, always dispose images when you no longer need them. Alternatively, call the convenience method image.dispose() directly on the GeoPackageImage instance.

createImage()

Decodes raw bytes, a data URL, or a Blob into a GeoPackageImage.
static async createImage(
  data: Uint8Array | Buffer | string,
  contentType?: string
): Promise<GeoPackageImage>
data
Uint8Array | Buffer | string
required
Raw image bytes, a base64 data URL, or a Blob.
contentType
string
MIME type of the image data. Defaults to 'image/png'.

toDataURL()

Encodes the current content of a canvas as a base64 data URL.
static async toDataURL(
  canvas: any,
  format?: string,
  quality?: number
): Promise<string>
canvas
any
required
The canvas to encode, previously created with Canvas.create().
format
string
MIME type for the output image. Defaults to 'image/png'.
quality
number
Compression quality from 0 to 1, used only by lossy formats such as 'image/jpeg'.

toBytes()

Encodes the current content of a canvas as a Uint8Array.
static toBytes(
  canvas: any,
  imageFormat?: ImageType,
  compressionQuality?: number
): Promise<Uint8Array>
canvas
any
required
The canvas to encode.
imageFormat
ImageType
Output format. Defaults to ImageType.PNG.
compressionQuality
number
Quality from 0 to 1 for lossy formats.

scaleImage()

Returns a new GeoPackageImage scaled by a uniform factor.
static scaleImage(
  image: GeoPackageImage,
  scale: number
): Promise<GeoPackageImage>
image
GeoPackageImage
required
The source image.
scale
number
required
Scale factor. Use 0.5 to halve the dimensions, 2 to double them.

scaleImageToDimensions()

Returns a new GeoPackageImage scaled to exact pixel dimensions.
static scaleImageToDimensions(
  image: GeoPackageImage,
  scaledWidth: number,
  scaledHeight: number
): Promise<GeoPackageImage>
image
GeoPackageImage
required
The source image.
scaledWidth
number
required
Target width in pixels.
scaledHeight
number
required
Target height in pixels.

getImageData()

Returns the raw pixel data of an image as an ImageData object.
static getImageData(image: GeoPackageImage): ImageData
image
GeoPackageImage
required
The image to read pixel data from.

measureText()

Returns the rendered width of a text string in pixels for the given font settings.
static measureText(
  context: CanvasRenderingContext2D,
  fontFace: string,
  fontSize: number,
  text: string
): number

drawText()

Draws text centred on a point inside a canvas rendering context.
static drawText(
  context: CanvasRenderingContext2D,
  text: string,
  location: number[],
  fontFace: string,
  fontSize: number,
  fontColor: string
): void
location
number[]
required
Two-element array [x, y] specifying the centre point for the text.

registerCanvasAdapter()

Registers a canvas adapter class. Called automatically by the context setup helpers; use this only when implementing a custom adapter.
static registerCanvasAdapter(adapter: new () => CanvasAdapter): void
adapter
new () => CanvasAdapter
required
A class (constructor) that implements the CanvasAdapter interface.

GeoPackageImage

GeoPackageImage wraps the adapter-specific image handle (an HTMLImageElement, a CanvasKit Image, or an ImageBitmap) together with its dimensions and MIME type.

Constructor

constructor(
  image: any,
  width: number,
  height: number,
  format?: string
)
In practice you obtain GeoPackageImage instances from Canvas.createImage() or ImageUtils.getImage() rather than constructing them directly.

Methods

getImage()

Returns the underlying adapter-specific image object.
public getImage(): any
The concrete type depends on the active adapter: HTMLImageElement (browser), a CanvasKit Image (Node.js), or ImageBitmap (Web Worker).

getWidth()

public getWidth(): number
Returns the image width in pixels.

getHeight()

public getHeight(): number
Returns the image height in pixels.

getFormat()

public getFormat(): string
Returns the MIME type string (e.g. 'image/png').

getImageType()

public getImageType(): ImageType
Returns the ImageType enum value corresponding to the image’s MIME type.

getImageData()

public getImageData(): ImageData
Returns the raw pixel data as an ImageData object. The result is cached after the first call. Internally calls Canvas.getImageData().

getPixel()

Returns the packed ARGB value of a single pixel.
public getPixel(x: number, y: number): number

isPixelTransparent()

Returns true if the alpha channel of the given pixel is zero.
public isPixelTransparent(x: number, y: number): boolean

dispose()

Convenience wrapper around Canvas.disposeImage(this). Call this in Node.js to free CanvasKit WASM memory.
public dispose(): void
Example — read tiles and dispose images in Node.js
import { GeoPackageManager, Canvas, ImageType } from '@ngageoint/geopackage';

const geoPackage = await GeoPackageManager.open('/data/world.gpkg');
try {
  const retriever = new GeoPackageTileRetriever(geoPackage, 'tiles', 256, 256);
  const image = await retriever.getTile(0, 0, 0);

  if (image) {
    console.log(`Tile size: ${image.getWidth()}x${image.getHeight()}`);
    // Write the tile to bytes
    const bytes = await Canvas.writeImageToBytes(image, ImageType.PNG, 1.0);
    // Always dispose in Node.js
    image.dispose();
  }
} finally {
  geoPackage.close();
}

Build docs developers (and LLMs) love