canvaskit-wasm
Version:
A WASM version of Skia's Canvas API
1,382 lines (1,244 loc) • 173 kB
TypeScript
// Minimum TypeScript Version: 4.4
/// <reference types="@webgpu/types" />
export default function CanvasKitInit(opts?: CanvasKitInitOptions): Promise<CanvasKit>;
export interface CanvasKitInitOptions {
/**
* This callback will be invoked when the CanvasKit loader needs to fetch a file (e.g.
* the blob of WASM code). The correct url prefix should be applied.
* @param file - the name of the file that is about to be loaded.
*/
locateFile(file: string): string;
}
export interface CanvasKit {
// Helpers
/**
* Constructs a Color with the same API as CSS's rgba(), that is
* Internally, Colors are four unpremultiplied 32-bit floats: r, g, b, a.
* In order to construct one with more precision or in a wider gamut,
* use CanvasKit.Color4f().
*
* @param r - red value, clamped to [0, 255].
* @param g - green value, clamped to [0, 255].
* @param b - blue value, clamped to [0, 255].
* @param a - alpha value, from 0 to 1.0. By default is 1.0 (opaque).
*/
Color(r: number, g: number, b: number, a?: number): Color;
/**
* Construct a 4-float color. Float values are typically between 0.0 and 1.0.
* @param r - red value.
* @param g - green value.
* @param b - blue value.
* @param a - alpha value. By default is 1.0 (opaque).
*/
Color4f(r: number, g: number, b: number, a?: number): Color;
/**
* Constructs a Color as a 32 bit unsigned integer, with 8 bits assigned to each channel.
* Channels are expected to be between 0 and 255 and will be clamped as such.
* If a is omitted, it will be 255 (opaque).
*
* This is not the preferred way to use colors in Skia APIs, use Color or Color4f.
* @param r - red value, clamped to [0, 255].
* @param g - green value, clamped to [0, 255].
* @param b - blue value, clamped to [0, 255].
* @param a - alpha value, from 0 to 1.0. By default is 1.0 (opaque).
*/
ColorAsInt(r: number, g: number, b: number, a?: number): ColorInt;
/**
* Returns a css style [r, g, b, a] where r, g, b are returned as
* ints in the range [0, 255] and where a is scaled between 0 and 1.0.
* [Deprecated] - this is trivial now that Color is 4 floats.
*/
getColorComponents(c: Color): number[];
/**
* Takes in a CSS color value and returns a CanvasKit.Color
* (which is an array of 4 floats in RGBA order). An optional colorMap
* may be provided which maps custom strings to values.
* In the CanvasKit canvas2d shim layer, we provide this map for processing
* canvas2d calls, but not here for code size reasons.
*/
parseColorString(color: string, colorMap?: Record<string, Color>): Color;
/**
* Returns a copy of the passed in color with a new alpha value applied.
* [Deprecated] - this is trivial now that Color is 4 floats.
*/
multiplyByAlpha(c: Color, alpha: number): Color;
/**
* Computes color values for one-pass tonal alpha.
* Note, if malloced colors are passed in, the memory pointed at by the MallocObj
* will be overwritten with the computed tonal colors (and thus the return val can be
* ignored).
* @param colors
*/
computeTonalColors(colors: TonalColorsInput): TonalColorsOutput;
/**
* Returns a rectangle with the given paramaters. See Rect.h for more.
* @param left - The x coordinate of the upper-left corner.
* @param top - The y coordinate of the upper-left corner.
* @param right - The x coordinate of the lower-right corner.
* @param bottom - The y coordinate of the lower-right corner.
*/
LTRBRect(left: number, top: number, right: number, bottom: number): Rect;
/**
* Returns a rectangle with the given paramaters. See Rect.h for more.
* @param x - The x coordinate of the upper-left corner.
* @param y - The y coordinate of the upper-left corner.
* @param width - The width of the rectangle.
* @param height - The height of the rectangle.
*/
XYWHRect(x: number, y: number, width: number, height: number): Rect;
/**
* Returns a rectangle with the given integer paramaters. See Rect.h for more.
* @param left - The x coordinate of the upper-left corner.
* @param top - The y coordinate of the upper-left corner.
* @param right - The x coordinate of the lower-right corner.
* @param bottom - The y coordinate of the lower-right corner.
*/
LTRBiRect(left: number, top: number, right: number, bottom: number): IRect;
/**
* Returns a rectangle with the given paramaters. See Rect.h for more.
* @param x - The x coordinate of the upper-left corner.
* @param y - The y coordinate of the upper-left corner.
* @param width - The width of the rectangle.
* @param height - The height of the rectangle.
*/
XYWHiRect(x: number, y: number, width: number, height: number): IRect;
/**
* Returns a rectangle with rounded corners consisting of the given rectangle and
* the same radiusX and radiusY for all four corners.
* @param rect - The base rectangle.
* @param rx - The radius of the corners in the x direction.
* @param ry - The radius of the corners in the y direction.
*/
RRectXY(rect: InputRect, rx: number, ry: number): RRect;
/**
* Generate bounding box for shadows relative to path. Includes both the ambient and spot
* shadow bounds. This pairs with Canvas.drawShadow().
* See SkShadowUtils.h for more details.
* @param ctm - Current transformation matrix to device space.
* @param path - The occluder used to generate the shadows.
* @param zPlaneParams - Values for the plane function which returns the Z offset of the
* occluder from the canvas based on local x and y values (the current
* matrix is not applied).
* @param lightPos - The 3D position of the light relative to the canvas plane. This is
* independent of the canvas's current matrix.
* @param lightRadius - The radius of the disc light.
* @param flags - See SkShadowUtils.h; 0 means use default options.
* @param dstRect - if provided, the bounds will be copied into this rect instead of allocating
* a new one.
* @returns The bounding rectangle or null if it could not be computed.
*/
getShadowLocalBounds(ctm: InputMatrix, path: Path, zPlaneParams: InputVector3,
lightPos: InputVector3, lightRadius: number, flags: number,
dstRect?: Rect): Rect | null;
/**
* Malloc returns a TypedArray backed by the C++ memory of the
* given length. It should only be used by advanced users who
* can manage memory and initialize values properly. When used
* correctly, it can save copying of data between JS and C++.
* When used incorrectly, it can lead to memory leaks.
* Any memory allocated by CanvasKit.Malloc needs to be released with CanvasKit.Free.
*
* const mObj = CanvasKit.Malloc(Float32Array, 20);
* Get a TypedArray view around the malloc'd memory (this does not copy anything).
* const ta = mObj.toTypedArray();
* // store data into ta
* const cf = CanvasKit.ColorFilter.MakeMatrix(ta); // mObj could also be used.
*
* // eventually...
* CanvasKit.Free(mObj);
*
* @param typedArray - constructor for the typedArray.
* @param len - number of *elements* to store.
*/
Malloc(typedArray: TypedArrayConstructor, len: number): MallocObj;
/**
* As Malloc but for GlyphIDs. This helper exists to make sure the JS side and the C++ side
* stay in agreement with how wide GlyphIDs are.
* @param len - number of GlyphIDs to make space for.
*/
MallocGlyphIDs(len: number): MallocObj;
/**
* Free frees the memory returned by Malloc.
* Any memory allocated by CanvasKit.Malloc needs to be released with CanvasKit.Free.
*/
Free(m: MallocObj): void;
// Surface related functions
/**
* Creates a Surface on a given canvas. If both GPU and CPU modes have been compiled in, this
* will first try to create a GPU surface and then fallback to a CPU one if that fails. If just
* the CPU mode has been compiled in, a CPU surface will be created.
* @param canvas - either a canvas or a string with the DOM id of it.
* @deprecated - Use MakeSWCanvasSurface, MakeWebGLCanvasSurface, or MakeGPUCanvasSurface.
*/
MakeCanvasSurface(canvas: HTMLCanvasElement | OffscreenCanvas | string): Surface | null;
/**
* Creates a Raster (CPU) Surface that will draw into the provided Malloc'd buffer. This allows
* clients to efficiently be able to read the current pixels w/o having to copy.
* The length of pixels must be at least height * bytesPerRow bytes big.
* @param ii
* @param pixels
* @param bytesPerRow - How many bytes are per row. This is at least width * bytesPerColorType. For example,
* an 8888 ColorType has 4 bytes per pixel, so a 5 pixel wide 8888 surface needs at least
* 5 * 4 = 20 bytesPerRow. Some clients may have more than the usual to make the data line
* up with a particular multiple.
*/
MakeRasterDirectSurface(ii: ImageInfo, pixels: MallocObj, bytesPerRow: number): Surface | null;
/**
* Creates a CPU backed (aka raster) surface.
* @param canvas - either a canvas or a string with the DOM id of it.
*/
MakeSWCanvasSurface(canvas: HTMLCanvasElement | OffscreenCanvas | string): Surface | null;
/**
* A helper for creating a WebGL backed (aka GPU) surface and falling back to a CPU surface if
* the GPU one cannot be created. This works for both WebGL 1 and WebGL 2.
* @param canvas - Either a canvas or a string with the DOM id of it.
* @param colorSpace - One of the supported color spaces. Default is SRGB.
* @param opts - Options that will get passed to the creation of the WebGL context.
*/
MakeWebGLCanvasSurface(canvas: HTMLCanvasElement | OffscreenCanvas | string,
colorSpace?: ColorSpace,
opts?: WebGLOptions): Surface | null;
/**
* Returns a CPU backed surface with the given dimensions, an SRGB colorspace, Unpremul
* alphaType and 8888 color type. The pixels belonging to this surface will be in memory and
* not visible.
* @param width - number of pixels of the width of the drawable area.
* @param height - number of pixels of the height of the drawable area.
*/
MakeSurface(width: number, height: number): Surface | null;
/**
* Creates a WebGL Context from the given canvas with the given options. If options are omitted,
* sensible defaults will be used.
* @param canvas
* @param opts
*/
GetWebGLContext(canvas: HTMLCanvasElement | OffscreenCanvas,
opts?: WebGLOptions): WebGLContextHandle;
/**
* Creates a GrDirectContext from the given WebGL Context.
* @param ctx
* @deprecated Use MakeWebGLContext instead.
*/
MakeGrContext(ctx: WebGLContextHandle): GrDirectContext | null;
/**
* Creates a GrDirectContext from the given WebGL Context.
* @param ctx
*/
MakeWebGLContext(ctx: WebGLContextHandle): GrDirectContext | null;
/**
* Creates a Surface that will be drawn to the given GrDirectContext (and show up on screen).
* @param ctx
* @param width - number of pixels of the width of the visible area.
* @param height - number of pixels of the height of the visible area.
* @param colorSpace
* @param sampleCount - sample count value from GL_SAMPLES. If not provided this will be looked up from
* the canvas.
* @param stencil - stencil count value from GL_STENCIL_BITS. If not provided this will be looked up
* from the WebGL Context.
*/
MakeOnScreenGLSurface(ctx: GrDirectContext, width: number, height: number,
colorSpace: ColorSpace, sampleCount?: number, stencil?: number): Surface | null;
/**
* Creates a context that operates over the given WebGPU Device.
* @param device
*/
MakeGPUDeviceContext(device: GPUDevice): WebGPUDeviceContext | null;
/**
* Creates a Surface that draws to the given GPU texture.
* @param ctx
* @param texture - A texture that was created on the GPU device associated with `ctx`.
* @param width - Width of the visible region in pixels.
* @param height - Height of the visible region in pixels.
* @param colorSpace
*/
MakeGPUTextureSurface(ctx: WebGPUDeviceContext, texture: GPUTexture, width: number, height: number,
colorSpace: ColorSpace): Surface | null;
/**
* Creates and configures a WebGPU context for the given canvas.
* @param ctx
* @param canvas
* @param opts
*/
MakeGPUCanvasContext(ctx: WebGPUDeviceContext, canvas: HTMLCanvasElement,
opts?: WebGPUCanvasOptions): WebGPUCanvasContext | null;
/**
* Creates a Surface backed by the next available texture in the swapchain associated with the
* given WebGPU canvas context. The context must have been already successfully configured using
* the same GPUDevice associated with `ctx`.
* @param canvasContext - WebGPU context associated with the canvas. The canvas can either be an
* on-screen HTMLCanvasElement or an OffscreenCanvas.
* @param colorSpace
* @param width - width of the visible region. If not present, the canvas width from `canvasContext`
* is used.
* @param height - height of the visible region. If not present, the canvas width from `canvasContext`
* is used.
*/
MakeGPUCanvasSurface(canvasContext: WebGPUCanvasContext, colorSpace: ColorSpace,
width?: number, height?: number): Surface | null;
/**
* Returns a (non-visible) Surface on the GPU. It has the given dimensions and uses 8888
* color depth and premultiplied alpha. See Surface.h for more details.
* @param ctx
* @param width
* @param height
*/
MakeRenderTarget(ctx: GrDirectContext, width: number, height: number): Surface | null;
/**
* Returns a (non-visible) Surface on the GPU. It has the settings provided by image info.
* See Surface.h for more details.
* @param ctx
* @param info
*/
MakeRenderTarget(ctx: GrDirectContext, info: ImageInfo): Surface | null;
/**
* Returns a texture-backed image based on the content in src. It assumes the image is
* RGBA_8888, unpremul and SRGB. This image can be re-used across multiple surfaces.
*
* Not available for software-backed surfaces.
* @param src - CanvasKit will take ownership of the TextureSource and clean it up when
* the image is destroyed.
* @param info - If provided, will be used to determine the width/height/format of the
* source image. If not, sensible defaults will be used.
* @param srcIsPremul - set to true if the src data has premultiplied alpha. Otherwise, it will
* be assumed to be Unpremultiplied. Note: if this is true and info specifies
* Unpremul, Skia will not convert the src pixels first.
*/
MakeLazyImageFromTextureSource(src: TextureSource, info?: ImageInfo | PartialImageInfo,
srcIsPremul?: boolean): Image;
/**
* Deletes the associated WebGLContext. Function not available on the CPU version.
* @param ctx
*/
deleteContext(ctx: WebGLContextHandle): void;
/**
* Returns the max size of the global cache for bitmaps used by CanvasKit.
*/
getDecodeCacheLimitBytes(): number;
/**
* Returns the current size of the global cache for bitmaps used by CanvasKit.
*/
getDecodeCacheUsedBytes(): number;
/**
* Sets the max size of the global cache for bitmaps used by CanvasKit.
* @param size - number of bytes that can be used to cache bitmaps.
*/
setDecodeCacheLimitBytes(size: number): void;
/**
* Decodes the given bytes into an animated image. Returns null if the bytes were invalid.
* The passed in bytes will be copied into the WASM heap, so the caller can dispose of them.
*
* The returned AnimatedImage will be "pointing to" the first frame, i.e. currentFrameDuration
* and makeImageAtCurrentFrame will be referring to the first frame.
* @param bytes
*/
MakeAnimatedImageFromEncoded(bytes: Uint8Array | ArrayBuffer): AnimatedImage | null;
/**
* Returns an emulated Canvas2D of the given size.
* @param width
* @param height
*/
MakeCanvas(width: number, height: number): EmulatedCanvas2D;
/**
* Returns an image with the given pixel data and format.
* Note that we will always make a copy of the pixel data, because of inconsistencies in
* behavior between GPU and CPU (i.e. the pixel data will be turned into a GPU texture and
* not modifiable after creation).
*
* @param info
* @param bytes - bytes representing the pixel data.
* @param bytesPerRow
*/
MakeImage(info: ImageInfo, bytes: number[] | Uint8Array | Uint8ClampedArray,
bytesPerRow: number): Image | null;
/**
* Return an Image backed by the encoded data, but attempt to defer decoding until the image
* is actually used/drawn. This deferral allows the system to cache the result, either on the
* CPU or on the GPU, depending on where the image is drawn.
* This decoding uses the codecs that have been compiled into CanvasKit. If the bytes are
* invalid (or an unrecognized codec), null will be returned. See Image.h for more details.
* @param bytes
*/
MakeImageFromEncoded(bytes: Uint8Array | ArrayBuffer): Image | null;
/**
* Returns an Image with the data from the provided CanvasImageSource (e.g. <img>). This will
* use the browser's built in codecs, in that src will be drawn to a canvas and then readback
* and placed into an Image.
* @param src
*/
MakeImageFromCanvasImageSource(src: CanvasImageSource): Image;
/**
* Returns an SkPicture which has been serialized previously to the given bytes.
* @param bytes
*/
MakePicture(bytes: Uint8Array | ArrayBuffer): SkPicture | null;
/**
* Returns an Vertices based on the given positions and optional parameters.
* See SkVertices.h (especially the Builder) for more details.
* @param mode
* @param positions
* @param textureCoordinates
* @param colors - either a list of int colors or a flattened color array.
* @param indices
* @param isVolatile
*/
MakeVertices(mode: VertexMode, positions: InputFlattenedPointArray,
textureCoordinates?: InputFlattenedPointArray | null,
colors?: Float32Array | ColorIntArray | null, indices?: number[] | null,
isVolatile?: boolean): Vertices;
/**
* Returns a Skottie animation built from the provided json string.
* Requires that Skottie be compiled into CanvasKit.
* Note: this animation will not be able to display text or images.
* @param json
*/
MakeAnimation(json: string): SkottieAnimation;
/**
* Returns a managed Skottie animation built from the provided json string and assets.
* Requires that Skottie be compiled into CanvasKit.
* @param json
* @param assets - a dictionary of named blobs: { key: ArrayBuffer, ... }
* @param filterPrefix - an optional string acting as a name filter for selecting "interesting"
* Lottie properties (surfaced in the embedded player controls)
* @param soundMap - an optional mapping of sound identifiers (strings) to AudioPlayers.
* Only needed if the animation supports sound.
*/
MakeManagedAnimation(json: string, assets?: Record<string, ArrayBuffer>,
filterPrefix?: string, soundMap?: SoundMap): ManagedSkottieAnimation;
// Constructors, i.e. things made with `new CanvasKit.Foo()`;
readonly ImageData: ImageDataConstructor;
readonly ParagraphStyle: ParagraphStyleConstructor;
readonly ContourMeasureIter: ContourMeasureIterConstructor;
readonly Font: FontConstructor;
readonly Paint: DefaultConstructor<Paint>;
readonly Path: PathConstructorAndFactory;
readonly PictureRecorder: DefaultConstructor<PictureRecorder>;
readonly TextStyle: TextStyleConstructor;
readonly SlottableTextProperty: SlottableTextPropertyConstructor;
// Factories, i.e. things made with CanvasKit.Foo.MakeTurboEncabulator()
readonly ParagraphBuilder: ParagraphBuilderFactory;
readonly Blender: BlenderFactory;
readonly ColorFilter: ColorFilterFactory;
readonly FontCollection: FontCollectionFactory;
readonly FontMgr: FontMgrFactory;
readonly ImageFilter: ImageFilterFactory;
readonly MaskFilter: MaskFilterFactory;
readonly PathEffect: PathEffectFactory;
readonly RuntimeEffect: RuntimeEffectFactory;
readonly Shader: ShaderFactory;
readonly TextBlob: TextBlobFactory;
readonly Typeface: TypefaceFactory;
readonly TypefaceFontProvider: TypefaceFontProviderFactory;
// Misc
readonly ColorMatrix: ColorMatrixHelpers;
readonly Matrix: Matrix3x3Helpers;
readonly M44: Matrix4x4Helpers;
readonly Vector: VectorHelpers;
// Core Enums
readonly AlphaType: AlphaTypeEnumValues;
readonly BlendMode: BlendModeEnumValues;
readonly BlurStyle: BlurStyleEnumValues;
readonly ClipOp: ClipOpEnumValues;
readonly ColorChannel: ColorChannelEnumValues;
readonly ColorType: ColorTypeEnumValues;
readonly FillType: FillTypeEnumValues;
readonly FilterMode: FilterModeEnumValues;
readonly FontEdging: FontEdgingEnumValues;
readonly FontHinting: FontHintingEnumValues;
readonly GlyphRunFlags: GlyphRunFlagValues;
readonly ImageFormat: ImageFormatEnumValues;
readonly MipmapMode: MipmapModeEnumValues;
readonly PaintStyle: PaintStyleEnumValues;
readonly Path1DEffect: Path1DEffectStyleEnumValues;
readonly PathOp: PathOpEnumValues;
readonly PointMode: PointModeEnumValues;
readonly ColorSpace: ColorSpaceEnumValues;
readonly StrokeCap: StrokeCapEnumValues;
readonly StrokeJoin: StrokeJoinEnumValues;
readonly TileMode: TileModeEnumValues;
readonly VertexMode: VertexModeEnumValues;
readonly InputState: InputStateEnumValues;
readonly ModifierKey: ModifierKeyEnumValues;
// Core Constants
readonly TRANSPARENT: Color;
readonly BLACK: Color;
readonly WHITE: Color;
readonly RED: Color;
readonly GREEN: Color;
readonly BLUE: Color;
readonly YELLOW: Color;
readonly CYAN: Color;
readonly MAGENTA: Color;
readonly MOVE_VERB: number;
readonly LINE_VERB: number;
readonly QUAD_VERB: number;
readonly CONIC_VERB: number;
readonly CUBIC_VERB: number;
readonly CLOSE_VERB: number;
readonly SaveLayerInitWithPrevious: SaveLayerFlag;
readonly SaveLayerF16ColorType: SaveLayerFlag;
/**
* Use this shadow flag to indicate the occluding object is not opaque. Knowing that the
* occluder is opaque allows us to cull shadow geometry behind it and improve performance.
*/
readonly ShadowTransparentOccluder: number;
/**
* Use this shadow flag to not use analytic shadows.
*/
readonly ShadowGeometricOnly: number;
/**
* Use this shadow flag to indicate the light position represents a direction and light radius
* is blur radius at elevation 1.
*/
readonly ShadowDirectionalLight: number;
readonly gpu?: boolean; // true if GPU code was compiled in
readonly managed_skottie?: boolean; // true if advanced (managed) Skottie code was compiled in
readonly rt_effect?: boolean; // true if RuntimeEffect was compiled in
readonly skottie?: boolean; // true if base Skottie code was compiled in
// Paragraph Enums
readonly Affinity: AffinityEnumValues;
readonly DecorationStyle: DecorationStyleEnumValues;
readonly FontSlant: FontSlantEnumValues;
readonly FontWeight: FontWeightEnumValues;
readonly FontWidth: FontWidthEnumValues;
readonly PlaceholderAlignment: PlaceholderAlignmentEnumValues;
readonly RectHeightStyle: RectHeightStyleEnumValues;
readonly RectWidthStyle: RectWidthStyleEnumValues;
readonly TextAlign: TextAlignEnumValues;
readonly TextBaseline: TextBaselineEnumValues;
readonly TextDirection: TextDirectionEnumValues;
readonly TextHeightBehavior: TextHeightBehaviorEnumValues;
// other enums
readonly VerticalTextAlign: VerticalTextAlignEnumValues;
readonly ResizePolicy: ResizePolicyEnumValues;
// Paragraph Constants
readonly NoDecoration: number;
readonly UnderlineDecoration: number;
readonly OverlineDecoration: number;
readonly LineThroughDecoration: number;
// Unicode enums
readonly CodeUnitFlags: CodeUnitFlagsEnumValues;
}
export interface Camera {
/** a 3d point locating the camera. */
eye: Vector3;
/** center of attention - the 3d point the camera is looking at. */
coa: Vector3;
/**
* A unit vector pointing the cameras up direction. Note that using only eye and coa
* would leave the roll of the camera unspecified.
*/
up: Vector3;
/** near clipping plane distance */
near: number;
/** far clipping plane distance */
far: number;
/** field of view in radians */
angle: AngleInRadians;
}
/**
* CanvasKit is built with Emscripten and Embind. Embind adds the following methods to all objects
* that are exposed with it.
* This _type field is necessary for the TypeScript compiler to differentiate
* between opaque types such as Shader and ColorFilter. It doesn't exist at runtime.
*/
export interface EmbindObject<T extends string> {
_type: T;
delete(): void;
deleteLater(): void;
isAliasOf(other: any): boolean;
isDeleted(): boolean;
}
/**
* Represents the set of enum values.
*/
export interface EmbindEnum {
readonly values: number[];
}
/**
* Represents a single member of an enum.
*/
export interface EmbindEnumEntity {
readonly value: number;
}
export interface EmulatedCanvas2D {
/**
* Cleans up all resources associated with this emulated canvas.
*/
dispose(): void;
/**
* Decodes an image with the given bytes.
* @param bytes
*/
decodeImage(bytes: ArrayBuffer | Uint8Array): Image;
/**
* Returns an emulated canvas2d context if type == '2d', null otherwise.
* @param type
*/
getContext(type: string): EmulatedCanvas2DContext | null;
/**
* Loads the given font with the given descriptors. Emulates new FontFace().
* @param bytes
* @param descriptors
*/
loadFont(bytes: ArrayBuffer | Uint8Array, descriptors: Record<string, string>): void;
/**
* Returns an new emulated Path2D object.
* @param str - an SVG string representing a path.
*/
makePath2D(str?: string): EmulatedPath2D;
/**
* Returns the current canvas as a base64 encoded image string.
* @param codec - image/png by default; image/jpeg also supported.
* @param quality
*/
toDataURL(codec?: string, quality?: number): string;
}
/** Part of the Canvas2D emulation code */
export type EmulatedCanvas2DContext = CanvasRenderingContext2D;
export type EmulatedImageData = ImageData;
export type EmulatedPath2D = Path2D;
export interface FontStyle {
weight?: FontWeight;
width?: FontWidth;
slant?: FontSlant;
}
/**
* See GrDirectContext.h for more on this class.
*/
export interface GrDirectContext extends EmbindObject<"GrDirectContext"> {
getResourceCacheLimitBytes(): number;
getResourceCacheUsageBytes(): number;
releaseResourcesAndAbandonContext(): void;
setResourceCacheLimitBytes(bytes: number): void;
}
/**
* Represents the context backed by a WebGPU device instance.
*/
export type WebGPUDeviceContext = GrDirectContext;
/**
* Represents the canvas context and swapchain backed by a WebGPU device.
*/
export interface WebGPUCanvasContext {
/**
* A convenient way to draw multiple frames over the swapchain texture sequence associated with
* a canvas element. Each call internally constructs a new Surface that targets the current
* GPUTexture in swapchain.
*
* This requires an environment where a global function called requestAnimationFrame is
* available (e.g. on the web, not on Node). The internally created surface is flushed and
* destroyed automatically by this wrapper once the `drawFrame` callback returns.
*
* Users can call canvasContext.requestAnimationFrame in the callback function to
* draw multiple frames, e.g. of an animation.
*/
requestAnimationFrame(drawFrame: (_: Canvas) => void): void;
}
/**
* The glyph and grapheme cluster information associated with a code point within
* a paragraph.
*/
export interface GlyphInfo {
/**
* The layout bounds of the grapheme cluster the code point belongs to, in
* the paragraph's coordinates.
*
* This width of the rect is horizontal advance of the grapheme cluster,
* the height of the rect is the line height when the grapheme cluster
* occupies a full line.
*/
graphemeLayoutBounds: Rect;
/**
* The left-closed-right-open UTF-16 range of the grapheme cluster the code
* point belongs to.
*/
graphemeClusterTextRange: URange;
/** The writing direction of the grapheme cluster. */
dir: TextDirection;
/**
* Whether the associated glyph points to an ellipsis added by the text
* layout library.
*
* The text layout library truncates the lines that exceed the specified
* max line number, and may add an ellipsis to replace the last few code
* points near the logical end of the last visible line. If True, this object
* marks the logical end of the list of GlyphInfo objects that are
* retrievable from the text layout library.
*/
isEllipsis: boolean;
}
/**
* See Metrics.h for more on this struct.
*/
export interface LineMetrics {
/** The index in the text buffer the line begins. */
startIndex: number;
/** The index in the text buffer the line ends. */
endIndex: number;
endExcludingWhitespaces: number;
endIncludingNewline: number;
/** True if the line ends in a hard break (e.g. newline) */
isHardBreak: boolean;
/**
* The final computed ascent for the line. This can be impacted by
* the strut, height, scaling, as well as outlying runs that are very tall.
*/
ascent: number;
/**
* The final computed descent for the line. This can be impacted by
* the strut, height, scaling, as well as outlying runs that are very tall.
*/
descent: number;
/** round(ascent + descent) */
height: number;
/** width of the line */
width: number;
/** The left edge of the line. The right edge can be obtained with `left + width` */
left: number;
/** The y position of the baseline for this line from the top of the paragraph. */
baseline: number;
/** Zero indexed line number. */
lineNumber: number;
}
export interface Range {
first: number;
last: number;
}
/**
* Information for a run of shaped text. See Paragraph.getShapedLines()
*
* Notes:
* positions is documented as Float32, but it holds twice as many as you expect, and they
* are treated logically as pairs of floats: {x0, y0}, {x1, y1}, ... for each glyph.
*
* positions and offsets arrays have 1 extra slot (actually 2 for positions)
* to describe the location "after" the last glyph in the glyphs array.
*/
export interface GlyphRun {
typeface: Typeface; // currently set to null (temporary)
size: number;
fakeBold: boolean;
fakeItalic: boolean;
glyphs: Uint16Array;
positions: Float32Array; // alternating x0, y0, x1, y1, ...
offsets: Uint32Array;
flags: number; // see GlyphRunFlags
}
/**
* Information for a paragraph of text. See Paragraph.getShapedLines()
*/
export interface ShapedLine {
textRange: Range; // first and last character offsets for the line (derived from runs[])
top: number; // top y-coordinate for the line
bottom: number; // bottom y-coordinate for the line
baseline: number; // baseline y-coordinate for the line
runs: GlyphRun[]; // array of GlyphRun objects for the line
}
/**
* Input to ShapeText(..., FontBlock[], ...);
*/
export interface FontBlock {
length: number; // number of text codepoints this block is applied to
typeface: Typeface;
size: number;
fakeBold: boolean;
fakeItalic: boolean;
}
/**
* This object is a wrapper around a pointer to some memory on the WASM heap. The type of the
* pointer was determined at creation time.
*/
export interface MallocObj {
/**
* The number of objects this pointer refers to.
*/
readonly length: number;
/**
* The "pointer" into the WASM memory. Should be fixed over the lifetime of the object.
*/
readonly byteOffset: number;
/**
* Return a read/write view into a subset of the memory. Do not cache the TypedArray this
* returns, it may be invalidated if the WASM heap is resized. This is the same as calling
* .toTypedArray().subarray() except the returned TypedArray can also be passed into an API
* and not cause an additional copy.
*/
subarray(start: number, end: number): TypedArray;
/**
* Return a read/write view of the memory. Do not cache the TypedArray this returns, it may be
* invalidated if the WASM heap is resized. If this TypedArray is passed into a CanvasKit API,
* it will not be copied again, only the pointer will be re-used.
*/
toTypedArray(): TypedArray;
}
/**
* This represents a subset of an animation's duration.
*/
export interface AnimationMarker {
name: string;
t0: number; // 0.0 to 1.0
t1: number; // 0.0 to 1.0
}
/**
* This object maintains a single audio layer during skottie playback
*/
export interface AudioPlayer {
/**
* Playback control callback, emitted for each corresponding Animation::seek().
*
* Will seek to time t (seconds) relative to the layer's timeline origin.
* Negative t values are used to signal off state (stop playback outside layer span).
*/
seek(t: number): void;
}
/**
* Mapping of sound names (strings) to AudioPlayers
*/
export interface SoundMap {
/**
* Returns AudioPlayer for a certain audio layer
* @param key string identifier, name of audio file the desired AudioPlayer manages
*/
getPlayer(key: string): AudioPlayer;
}
/**
* Named color property.
*/
export interface ColorProperty {
/**
* Property identifier, usually the node name.
*/
key: string;
/**
* Property value (RGBA, 255-based).
*/
value: ColorInt;
}
/**
* Named opacity property.
*/
export interface OpacityProperty {
/**
* Property identifier, usually the node name.
*/
key: string;
/**
* Property value (0..100).
*/
value: number;
}
/**
* Text property value.
*/
export interface TextValue {
/**
* The text string payload.
*/
text: string;
/**
* Font size.
*/
size: number;
}
/**
* Named text property.
*/
export interface TextProperty {
/**
* Property identifier, usually the node name.
*/
key: string;
/**
* Property value.
*/
value: TextValue;
}
/**
* Transform property value. Maps to AE styled transform.
*/
export interface TransformValue {
/**
* Anchor point for transform. x and y value.
*/
anchor: Point;
/**
* Position of transform. x and y value.
*/
position: Point;
/**
* Scale of transform. x and y value.
*/
scale: Vector2;
/**
* Rotation of transform in degrees.
*/
rotation: number;
/**
* Skew to apply during transform.
*/
skew: number;
/**
* Direction of skew in degrees.
*/
skew_axis: number;
}
/**
* Named transform property for Skottie property observer.
*/
export interface TransformProperty {
/**
* Property identifier, usually the node name.
*/
key: string;
/**
* Property value.
*/
value: TransformValue;
}
/**
* Collection of slot IDs sorted by value type
*/
export interface SlotInfo {
colorSlotIDs: string[];
scalarSlotIDs: string[];
vec2SlotIDs: string[];
imageSlotIDs: string[];
textSlotIDs: string[];
}
/**
* Text property for ManagedAnimation's slot support
*/
export interface SlottableTextProperty {
typeface?: Typeface;
text?: string;
textSize?: number;
minTextSize?: number;
maxTextSize?: number;
strokeWidth?: number;
lineHeight?: number;
lineShift?: number;
ascent?: number;
maxLines?: number;
horizAlign?: TextAlignEnumValues;
vertAlign?: VerticalTextAlignEnumValues;
strokeJoin?: StrokeJoinEnumValues;
direction?: TextDirectionEnumValues;
linebreak?: LineBreakTypeEnumValues;
resize?: ResizePolicyEnumValues;
boundingBox?: InputRect;
fillColor?: InputColor;
strokeColor?: InputColor;
}
export interface ManagedSkottieAnimation extends SkottieAnimation {
setColor(key: string, color: InputColor): boolean;
setOpacity(key: string, opacity: number): boolean;
setText(key: string, text: string, size: number): boolean;
setTransform(key: string, anchor: InputPoint, position: InputPoint, scale: InputVector2,
rotation: number, skew: number, skew_axis: number): boolean;
getMarkers(): AnimationMarker[];
getColorProps(): ColorProperty[];
getOpacityProps(): OpacityProperty[];
getTextProps(): TextProperty[];
getTransformProps(): TransformProperty[];
// Slots in Lottie were exposed with bodymovin version 5.11.0
// Properties tracked under the Essential Graphics window in AE will be "slotted". These slots
// can be observed and editted live like with the other get/set tools. The slot id passed in
// must match the name of the property in the Essential Graphics window. Property Groups support
// one-to-many relationships.
getSlotInfo(): SlotInfo;
setColorSlot(key: string, color: InputColor): boolean;
setScalarSlot(key: string, scalar: number): boolean;
setVec2Slot(key: string, vec2: InputVector2): boolean;
setTextSlot(key: string, text: SlottableTextProperty): boolean;
setImageSlot(key: string, assetName: string): boolean;
getColorSlot(key: string): Color | null;
getScalarSlot(key: string): number | null;
getVec2Slot(key: string): Vector2 | null;
getTextSlot(key: string): SlottableTextProperty | null;
// Attach a WYSIWYG editor to the text layer identified by 'id' and 'index' (multiple layers
// can be grouped with the same ID).
// Other layers with the same ID are attached as dependents, and updated on the fly as the
// edited layer changes.
attachEditor(id: string, index: number): boolean;
// Enable/disable the current editor.
enableEditor(enable: boolean): void;
// Send key events to the active editor.
dispatchEditorKey(key: string): boolean;
// Send pointer events to the active editor, in canvas coordinates.
dispatchEditorPointer(x: number, y: number, state: InputState, modifier: ModifierKey): boolean;
// Adjust the relative cursor weight (default: 1).
setEditorCursorWeight(w: number): void;
}
/**
* See Paragraph.h for more information on this class. This is only available if Paragraph has
* been compiled in.
*/
export interface Paragraph extends EmbindObject<"Paragraph"> {
didExceedMaxLines(): boolean;
getAlphabeticBaseline(): number;
/**
* Returns the index of the glyph that corresponds to the provided coordinate,
* with the top left corner as the origin, and +y direction as down.
*/
getGlyphPositionAtCoordinate(dx: number, dy: number): PositionWithAffinity;
/**
* Returns the information associated with the closest glyph at the specified
* paragraph coordinate, or null if the paragraph is empty.
*/
getClosestGlyphInfoAtCoordinate(dx: number, dy: number): GlyphInfo | null;
/**
* Returns the information associated with the glyph at the specified UTF-16
* offset within the paragraph's visible lines, or null if the index is out
* of bounds, or points to a codepoint that is logically after the last
* visible codepoint.
*/
getGlyphInfoAt(index: number): GlyphInfo | null;
getHeight(): number;
getIdeographicBaseline(): number;
/**
* Returns the line number of the line that contains the specified UTF-16
* offset within the paragraph, or -1 if the index is out of bounds, or
* points to a codepoint that is logically after the last visible codepoint.
*/
getLineNumberAt(index: number): number;
getLineMetrics(): LineMetrics[];
/**
* Returns the LineMetrics of the line at the specified line number, or null
* if the line number is out of bounds, or is larger than or equal to the
* specified max line number.
*/
getLineMetricsAt(lineNumber: number): LineMetrics | null;
getLongestLine(): number;
getMaxIntrinsicWidth(): number;
getMaxWidth(): number;
getMinIntrinsicWidth(): number;
/**
* Returns the total number of visible lines in the paragraph.
*/
getNumberOfLines(): number;
getRectsForPlaceholders(): RectWithDirection[];
/**
* Returns bounding boxes that enclose all text in the range of glpyh indexes [start, end).
* @param start
* @param end
* @param hStyle
* @param wStyle
*/
getRectsForRange(start: number, end: number, hStyle: RectHeightStyle,
wStyle: RectWidthStyle): RectWithDirection[];
/**
* Finds the first and last glyphs that define a word containing the glyph at index offset.
* @param offset
*/
getWordBoundary(offset: number): URange;
/**
* Returns an array of ShapedLine objects, describing the paragraph.
*/
getShapedLines(): ShapedLine[];
/**
* Lays out the text in the paragraph so it is wrapped to the given width.
* @param width
*/
layout(width: number): void;
/**
* When called after shaping, returns the glyph IDs which were not matched
* by any of the provided fonts.
*/
unresolvedCodepoints(): number[];
}
export interface ParagraphBuilder extends EmbindObject<"ParagraphBuilder"> {
/**
* Pushes the information required to leave an open space.
* @param width
* @param height
* @param alignment
* @param baseline
* @param offset
*/
addPlaceholder(width?: number, height?: number, alignment?: PlaceholderAlignment,
baseline?: TextBaseline, offset?: number): void;
/**
* Adds text to the builder. Forms the proper runs to use the upper-most style
* on the style_stack.
* @param str
*/
addText(str: string): void;
/**
* Returns a Paragraph object that can be used to be layout and paint the text to an
* Canvas.
*/
build(): Paragraph;
/**
* @param words is an array of word edges (starting or ending). You can
* pass 2 elements (0 as a start of the entire text and text.size as the
* end). This information is only needed for a specific API method getWords.
*
* The indices are expected to be relative to the UTF-8 representation of
* the text.
*/
setWordsUtf8(words: InputWords): void;
/**
* @param words is an array of word edges (starting or ending). You can
* pass 2 elements (0 as a start of the entire text and text.size as the
* end). This information is only needed for a specific API method getWords.
*
* The indices are expected to be relative to the UTF-16 representation of
* the text.
*
* The `Intl.Segmenter` API can be used as a source for this data.
*/
setWordsUtf16(words: InputWords): void;
/**
* @param graphemes is an array of indexes in the input text that point
* to the start of each grapheme.
*
* The indices are expected to be relative to the UTF-8 representation of
* the text.
*/
setGraphemeBreaksUtf8(graphemes: InputGraphemes): void;
/**
* @param graphemes is an array of indexes in the input text that point
* to the start of each grapheme.
*
* The indices are expected to be relative to the UTF-16 representation of
* the text.
*
* The `Intl.Segmenter` API can be used as a source for this data.
*/
setGraphemeBreaksUtf16(graphemes: InputGraphemes): void;
/**
* @param lineBreaks is an array of unsigned integers that should be
* treated as pairs (index, break type) that point to the places of possible
* line breaking if needed. It should include 0 as the first element.
* Break type == 0 means soft break, break type == 1 is a hard break.
*
* The indices are expected to be relative to the UTF-8 representation of
* the text.
*/
setLineBreaksUtf8(lineBreaks: InputLineBreaks): void;
/**
* @param lineBreaks is an array of unsigned integers that should be
* treated as pairs (index, break type) that point to the places of possible
* line breaking if needed. It should include 0 as the first element.
* Break type == 0 means soft break, break type == 1 is a hard break.
*
* The indices are expected to be relative to the UTF-16 representation of
* the text.
*
* Chrome's `v8BreakIterator` API can be used as a source for this data.
*/
setLineBreaksUtf16(lineBreaks: InputLineBreaks): void;
/**
* Returns the entire Paragraph text (which is useful in case that text
* was produced as a set of addText calls).
*/
getText(): string;
/**
* Remove a style from the stack. Useful to apply different styles to chunks
* of text such as bolding.
*/
pop(): void;
/**
* Push a style to the stack. The corresponding text added with addText will
* use the top-most style.
* @param text
*/
pushStyle(text: TextStyle): void;
/**
* Pushes a TextStyle using paints instead of colors for foreground and background.
* @param textStyle
* @param fg
* @param bg
*/
pushPaintStyle(textStyle: TextStyle, fg: Paint, bg: Paint): void;
/**
* Resets this builder to its initial state, discarding any text, styles, placeholders that have
* been added, but keeping the initial ParagraphStyle.
*/
reset(): void;
}
export interface ParagraphStyle {
disableHinting?: boolean;
ellipsis?: string;
heightMultiplier?: number;
maxLines?: number;
replaceTabCharacters?: boolean;
strutStyle?: StrutStyle;
textAlign?: TextAlign;
textDirection?: TextDirection;
textHeightBehavior?: TextHeightBehavior;
textStyle?: TextStyle;
applyRoundingHack?: boolean;
}
export interface PositionWithAffinity {
pos: number;
affinity: Affinity;
}
export interface SkSLUniform {
columns: number;
rows: number;
/** The index into the uniforms array that this uniform begins. */
slot: number;
isInteger: boolean;
}
/**
* See SkAnimatedImage.h for more information on this class.
*/
export interface AnimatedImage extends EmbindObject<"AnimatedImage"> {
/**
* Returns the length of the current frame in ms.
*/
currentFrameDuration(): number;
/**
* Decodes the next frame. Returns the length of that new frame in ms.
* Returns -1 when the animation is on the last frame.
*/
decodeNextFrame(): number;
/**
* Return the total number of frames in the animation.
*/
getFrameCount(): number;
/**
* Return the repetition count for this animation.
*/
getRepetitionCount(): number;
/**
* Returns the possibly scaled height of the image.
*/
height(): number;
/**
* Returns a still image of the current frame or null if there is no current frame.
*/
makeImageAtCurrentFrame(): Image | null;
/**
* Reset the animation to the beginning.
*/
reset(): void;
/**
* Returns the possibly scaled width of the image.
*/
width(): number;
}
/**
* See SkBlender.h for more on this class. The objects are opaque.
*/
export type Blender = EmbindObject<"Blender">;
/**
* See SkCanvas.h for more information on this class.
*/
export interface Canvas extends EmbindObject<"Canvas"> {
/**
* Fills the current clip with the given color using Src BlendMode.
* This has the effect of replacing all pixels contained by clip with color.
* @param color
*/
clear(color: InputColor): void;
/**
* Replaces clip with the intersection or difference of the current clip and path,
* with an aliased or anti-aliased clip edge.
* @param path
* @param op
* @param doAntiAlias
*/
clipPath(path: Path, op: ClipOp, doAntiAlias: boolean): void;
/**
* Replaces c