An HTML Canvas API implementation on top of android and iOS native APIs
npm install @nativescript-community/ui-htmlcanvasapiAn HTML Canvas implementation on top of @nativescript-community/ui-canvas.
Supported classes:
- OffscreenCanvas
- CanvasRenderingContext2D
- HTMLCanvasElement
- ImageBitmapRenderingContext
- OffscreenCanvasRenderingContext2D
- CanvasGradient
- CanvasPattern
- DOMMatrix
- DOMPoint (not used yet)
- Path2D
- TextMetrics
``javascript`
npm install @nativescript-community/ui-htmlcanvasapi
ts
import { Application } from '@nativescript/core';
import { installPolyfills } from '@nativescript-community/ui-htmlcanvasapi';installPolyfills();
Application.run({ moduleName: 'app-root' });
`Then, set up your view
`xml
``ts
import { Canvas } from '@nativescript-community/ui-canvas';
import { HTMLCanvasView } from '@nativescript-community/ui-htmlcanvasapi';export function onDraw(args: { object: HTMLCanvasView; canvas: Canvas }) {
const ctx = args.object.getContext('2d');
ctx.save();
ctx.fillStyle = 'yellow';
ctx.fillRect(10, 10, 200, 100);
ctx.transform(1, 0.5, -0.5, 1, 30, 10);
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 200, 100);
ctx.transform(1, 0.5, -0.5, 1, 30, 10);
ctx.fillStyle = 'blue';
ctx.fillRect(10, 10, 200, 100);
ctx.restore();
}
`Sometimes, there might be the need to draw things offscreen but keep reference to the view and eventually draw everything there.
An offscreen buffer can be enabled by setting
isOffscreenBufferEnabled to true.
Note: Everything will be drawn onto view canvas once app calls view invalidate() method. `xml
``ts
import { HTMLCanvasView } from '@nativescript-community/ui-htmlcanvasapi';
import { EventData, Page } from '@nativescript/core';function onNavigatedTo(args: EventData): void {
const page = args.object;
const canvasView = page.getViewById("canvasView");
const ctx = canvasView.getContext('2d');
ctx.save();
ctx.fillStyle = 'yellow';
ctx.fillRect(10, 10, 200, 100);
ctx.transform(1, 0.5, -0.5, 1, 30, 10);
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 200, 100);
ctx.transform(1, 0.5, -0.5, 1, 30, 10);
ctx.fillStyle = 'blue';
ctx.fillRect(10, 10, 200, 100);
ctx.restore();
// Draw everything to view
canvasView.invalidate();
}
``Apache License Version 2.0