Skip to content

Utility functions

toHTMLCanvasElement()

ts
declare function toHTMLCanvasElement(
  canvas: OffscreenCanvas | HTMLCanvasElement
): HTMLCanvasElement;
  • Param: canvas: OffscreenCanvas | HTMLCanvasElement
  • Returns: HTMLCanvasElemens

If OffscreenCanvas instance is passed to function, it creates new HTMLCanvasElement, draws offscreen canvas content on it, and returns it. If HTMLCanvasElement instance is passed, function returns it unchanged.

This may be useful if you need to insert distortion result canvas in DOM and is not sure if distorted image is OffscreenCanvas of HtmlCanvasElement.

Example:

ts
import { distortUnwrap, toHTMLCanvasElement } from "@alxcube/lens";

const insertInBody = (canvas: OffscreenCanvas | HTMLCanvasElement) =>
  document.body.appendChild(toHTMLCanvasElement(canvas));

const offscreenCanvas = new OffscreenCanvas(100, 100);
const elementCanvas = document.createElement("canvas");

// ... draw on Canvas

// distort
const results = await Promise.all(
  [offscreenCanvas, elementCanvas].map((canvas) =>
    distortUnwrap(canvas, "Arc", [180])
  )
);

results.forEach(insertInBody);

preloadHtmlImage()

ts
declare function preloadHtmlImage(
  src: string,
  image = new Image()
): Promise<HTMLImageElement>;
  • Params:
    • src: string
    • image?: HTMLImageElement
  • Returns: Promise<HTMLImageElement>

Returns promise which will be fulfilled with HTMLImageElement after it is completely loaded. If image argument is passed, uses it as preloader, and resolves returned promise with it. Otherwise, creates new HTMLImageElement for preloading. Rejects returned promise on loading error with Error instance.

makeCanvas()

ts
declare function makeCanvas(
  width: number,
  height: number,
  onscreen?: boolean
): OffscreenCanvas | HTMLCanvasElement;
  • Params:
    • width: number,
    • height: number,
    • onscreen?: boolean
  • Returns: OffscreenCanvas | HTMLCanvasElement

Returns canvas of given size. If onscreen argument is omitted or set to false, returns OffscreenCanvas. If onscreen is set to true, returns HTMLCanvasElement.