Skip to content

Rendering Contexts ​

@nativescript/canvas provides several context types, each suited to a different kind of work.

ContextBest forAPI style
2dUI drawing, charts, image compositionCanvas 2D spec
webglPortable GPU renderingWebGL 1 spec
webgl2Modern GL featuresWebGL 2 spec
webgpuNew GPU pipelines and compute workloadsWebGPU spec
bitmaprendererDisplaying an ImageBitmap produced elsewhereImageBitmapRenderingContext spec

Choosing a context ​

  • Use 2d for simple rendering and draw operations.
  • Use webgl or webgl2 for 3D scenes and shader-heavy visuals.
  • Use webgpu when you need newer GPU capabilities and explicit control over the pipeline.
  • Use bitmaprenderer when a frame is produced once, off screen or in another canvas, and you only need to present it.

Creating a context ​

ts
const ctx2d = canvas.getContext('2d');
const gl = canvas.getContext('webgl');
const gl2 = canvas.getContext('webgl2');
const gpu = canvas.getContext('webgpu'); // needs navigator.gpu from @nativescript/canvas-polyfill
const bitmap = canvas.getContext('bitmaprenderer');

A canvas holds only one kind of context. As on the web, asking a canvas for a different type than it already has returns null.

Context attributes ​

Pass attributes as the second argument, as you would on the web:

ts
const ctx = canvas.getContext('2d', { alpha: false, willReadFrequently: true });
const gl = canvas.getContext('webgl2', { antialias: false, preserveDrawingBuffer: true });
AttributeDefaultApplies to
alphatrueall
antialiastrueWebGL
depthtrueWebGL
stencilfalseWebGL
premultipliedAlphatrueWebGL
preserveDrawingBufferfalseWebGL
powerPreference'default'WebGL ('high-performance' or 'low-power')
failIfMajorPerformanceCaveatfalseWebGL
desynchronizedfalse2D, WebGL
willReadFrequentlyfalse2D. See Performance.

2D backends ​

The 2D context is drawn by Skia on the GPU:

PlatformDefaultFallback
iOS, tvOS, visionOSMetalGL, if you set Canvas.forceGL = true before getContext (not on visionOS)
AndroidVulkan (API 24+ with a supported driver)GL

willReadFrequently: true switches that canvas to a CPU raster surface instead.

bitmaprenderer ​

bitmaprenderer presents an ImageBitmap without copying it. transferFromImageBitmap resizes the canvas to fit the bitmap and detaches the bitmap. Passing null clears the canvas.

ts
const bitmap = await createImageBitmap(sourceCanvas);
const ctx = canvas.getContext('bitmaprenderer');
ctx.transferFromImageBitmap(bitmap);
// bitmap.width is now 0: it has been handed to the canvas.

Only the alpha attribute applies. See Images and ImageBitmap for the sources you can create a bitmap from.

Spec alignment ​

The package follows web API behavior where possible:

Sample guides ​