UNPKG

canvaskit-wasm

Version:

A WASM version of Skia's Canvas API

1,385 lines (1,235 loc) 130 kB
// Minimum TypeScript Version: 3.7 export 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?: object): 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 SkShadowFlags.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 the canvas element itself or a string with the DOM id of it. */ MakeCanvasSurface(canvas: HTMLCanvasElement | 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 the canvas element itself or a string with the DOM id of it. */ MakeSWCanvasSurface(canvas: HTMLCanvasElement | 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 the canvas element itself 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 | 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, opts?: WebGLOptions): WebGLContextHandle; /** * Creates a GrDirectContext from the given WebGL Context. * @param ctx */ MakeGrContext(ctx: WebGLContextHandle): GrDirectContext; /** * 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 */ MakeOnScreenGLSurface(ctx: GrDirectContext, width: number, height: number, colorSpace: ColorSpace): 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 the current WebGLContext that the wasm code is configured to draw to. It is * recommended to capture this value after creating a new WebGL surface if there are multiple * surfaces on the screen. */ currentContext(): WebGLContextHandle; /** * Sets the WebGLContext that the wasm code will draw to. * * When a WebGL call is made on the C++ side, it is routed to the JS side to target a specific * WebGL context. WebGL calls are methods on a WebGL context, so CanvasKit needs to know which * context to send the calls to. * @param ctx */ setCurrentContext(ctx: WebGLContextHandle): void; /** * 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. * @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. * @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; /** * Returns a Particles effect built from the provided json string and assets. * Requires that Particles be compiled into CanvasKit * @param json * @param assets */ MakeParticles(json: string, assets?: Record<string, ArrayBuffer>): Particles; // Constructors, i.e. things made with `new CanvasKit.Foo()`; readonly ImageData: ImageDataConstructor; readonly ParagraphStyle: ParagraphStyleConstructor; readonly ShapedText: ShapedTextConstructor; readonly ContourMeasureIter: ContourMeasureIterConstructor; readonly Font: FontConstructor; readonly Paint: DefaultConstructor<Paint>; readonly Path: PathConstructorAndFactory; readonly PictureRecorder: DefaultConstructor<PictureRecorder>; readonly TextStyle: TextStyleConstructor; // Factories, i.e. things made with CanvasKit.Foo.MakeTurboEncapsulator() readonly ParagraphBuilder: ParagraphBuilderFactory; readonly ColorFilter: ColorFilterFactory; readonly FontMgr: FontMgrFactory; readonly ImageFilter: ImageFilterFactory; readonly MaskFilter: MaskFilterFactory; readonly PathEffect: PathEffectFactory; readonly RuntimeEffect: RuntimeEffectFactory; readonly Shader: ShaderFactory; readonly TextBlob: TextBlobFactory; 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 ColorType: ColorTypeEnumValues; readonly FillType: FillTypeEnumValues; readonly FilterMode: FilterModeEnumValues; readonly FilterQuality: FilterQualityEnumValues; readonly FontEdging: FontEdgingEnumValues; readonly FontHinting: FontHintingEnumValues; readonly ImageFormat: ImageFormatEnumValues; readonly MipmapMode: MipmapModeEnumValues; readonly PaintStyle: PaintStyleEnumValues; readonly PathOp: PathOpEnumValues; readonly PointMode: PointModeEnumValues; readonly ColorSpace: ColorSpaceEnumValues; readonly StrokeCap: StrokeCapEnumValues; readonly StrokeJoin: StrokeJoinEnumValues; readonly TileMode: TileModeEnumValues; readonly VertexMode: VertexModeEnumValues; // 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; // if GPU 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; // Paragraph Constants readonly NoDecoration: number; readonly UnderlineDecoration: number; readonly OverlineDecoration: number; readonly LineThroughDecoration: number; } 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. */ export interface EmbindObject<T extends EmbindObject<T>> { clone(): T; delete(): void; deleteAfter(): 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: object): 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; } /** * 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; } /** * 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 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; } export interface ManagedSkottieAnimation extends SkottieAnimation { setColor(key: string, color: InputColor): void; setOpacity(key: string, opacity: number): void; getMarkers(): object[]; getColorProps(): object[]; getOpacityProps(): object[]; } /** * 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; getHeight(): number; getIdeographicBaseline(): number; getLineMetrics(): LineMetrics[]; getLongestLine(): number; getMaxIntrinsicWidth(): number; getMaxWidth(): number; getMinIntrinsicWidth(): number; getRectsForPlaceholders(): FlattenedRectangleArray; /** * 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): FlattenedRectangleArray; /** * Finds the first and last glyphs that define a word containing the glyph at index offset. * @param offset */ getWordBoundary(offset: number): URange; /** * Lays out the text in the paragraph so it is wrapped to the given width. * @param width */ layout(width: number): void; } 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; /** * 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; } export interface ParagraphStyle { disableHinting?: boolean; ellipsis?: string; heightMultiplier?: number; maxLines?: number; strutStyle?: StrutStyle; textAlign?: TextAlign; textDirection?: TextDirection; textStyle?: TextStyle; } export interface PositionWithAffinity { pos: number; affinity: Affinity; } /** * See SkParticleEffect.h for more details. */ export interface Particles extends EmbindObject<Particles> { /** * Draws the current state of the particles on the given canvas. * @param canvas */ draw(canvas: Canvas): void; /** * Returns a Float32Array bound to the WASM memory of these uniforms. Changing these * floats will change the corresponding uniforms instantly. */ uniforms(): Float32Array; /** * Returns the nth uniform from the effect. * @param index */ getUniform(index: number): SkSLUniform; /** * Returns the number of uniforms on the effect. */ getUniformCount(): number; /** * Returns the total number of floats across all uniforms on the effect. This is the length * of the array returned by `uniforms()`. For example, an effect with a single float3 uniform, * would return 1 from `getUniformCount()`, but 3 from `getUniformFloatCount()`. */ getUniformFloatCount(): number; /** * Returns the name of the nth effect uniform. * @param index */ getUniformName(index: number): string; /** * Sets the base position of the effect. * @param point */ setPosition(point: InputPoint): void; /** * Sets the base rate of the effect. * @param rate */ setRate(rate: number): void; /** * Starts playing the effect. * @param now * @param looping */ start(now: number, looping: boolean): void; /** * Updates the effect using the new time. * @param now */ update(now: number): void; } export interface SkSLUniform { columns: number; rows: number; /** The index into the uniforms array that this uniform begins. */ slot: number; } /** * A simple wrapper around TextBlob and the simple Text Shaper. */ export interface ShapedText extends EmbindObject<ShapedText> { /** * Return the bounding area for the given text. * @param outputArray - if provided, the bounding box will be copied into this array instead of * allocating a new one. */ getBounds(outputArray?: Rect): Rect; } export interface ShapedTextOpts { text: string; font: Font; leftToRight: boolean; width: number; } /** * See SkAnimatedImage.h for more information on this class. */ export interface AnimatedImage extends EmbindObject<AnimatedImage> { /** * Decodes the next frame. 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 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 clip with the intersection or difference of the current clip and rect, * with an aliased or anti-aliased clip edge. * @param rect * @param op * @param doAntiAlias */ clipRect(rect: InputRect, op: ClipOp, doAntiAlias: boolean): void; /** * Replaces clip with the intersection or difference of the current clip and rrect, * with an aliased or anti-aliased clip edge. * @param rrect * @param op * @param doAntiAlias */ clipRRect(rrect: InputRRect, op: ClipOp, doAntiAlias: boolean): void; /** * Replaces current matrix with m premultiplied with the existing matrix. * @param m */ concat(m: InputMatrix): void; /** * Draws arc using clip, Matrix, and Paint paint. * * Arc is part of oval bounded by oval, sweeping from startAngle to startAngle plus * sweepAngle. startAngle and sweepAngle are in degrees. * @param oval - bounds of oval containing arc to draw * @param startAngle - angle in degrees where arc begins * @param sweepAngle - sweep angle in degrees; positive is clockwise * @param useCenter - if true, include the center of the oval * @param paint */ drawArc(oval: InputRect, startAngle: AngleInDegrees, sweepAngle: AngleInDegrees, useCenter: boolean, paint: Paint): void; /** * Draws a set of sprites from atlas, using clip, Matrix, and optional Paint paint. * @param atlas - Image containing sprites * @param srcRects - Rect locations of sprites in atlas * @param dstXforms - RSXform mappings for sprites in atlas * @param paint * @param blendMode - BlendMode combining colors and sprites * @param colors - If provided, will be blended with sprite using blendMode. */ drawAtlas(atlas: Image, srcRects: InputFlattenedRectangleArray, dstXforms: InputFlattenedRSXFormArray, paint: Paint, blendMode?: BlendMode, colors?: ColorIntArray): void; /** * Draws a circle at (cx, cy) with the given radius. * @param cx * @param cy * @param radius * @param paint */ drawCircle(cx: number, cy: number, radius: number, paint: Paint): void; /** * Fills clip with the given color. * @param color * @param blendMode - defaults to SrcOver. */ drawColor(color: InputColor, blendMode?: BlendMode): void; /** * Fills clip with the given color. * @param r - red value (typically from 0 to 1.0). * @param g - green value (typically from 0 to 1.0). * @param b - blue value (typically from 0 to 1.0). * @param a - alpha value, range 0 to 1.0 (1.0 is opaque). * @param blendMode - defaults to SrcOver. */ drawColorComponents(r: number, g: number, b: number, a: number, blendMode?: BlendMode): void; /** * Fills clip with the given color. * @param color * @param blendMode - defaults to SrcOver. */ drawColorInt(color: ColorInt, blendMode?: BlendMode): void; /** * Draws RRect outer and inner using clip, Matrix, and Paint paint. * outer must contain inner or the drawing is undefined. * @param outer * @param inner * @param paint */ drawDRRect(outer: InputRRect, inner: InputRRect, paint: Paint): void; /** * Draws the given image with its top-left corner at (left, top) using the current clip, * the current matrix, and optionally-provided paint. * @param img * @param left * @param top * @param paint */ drawImage(img: Image, left: number, top: number, paint?: Paint): void; /** * Draws the given image with its top-left corner at (left, top) using the current clip, * the current matrix. It will use the cubic sampling options B and C if necessary. * @param img * @param left * @param top * @param B - See CubicResampler in SkSamplingOptions.h for more information * @param C - See CubicResampler in SkSamplingOptions.h for more information * @param paint */ drawImageCubic(img: Image, left: number, top: number, B: number, C: number, paint: Paint | null): void; /** * Draws the given image with its top-left corner at (left, top) using the current clip, * the current matrix. It will use the provided sampling options if necessary. * @param img * @param left * @param top * @param fm - The filter mode. * @param mm - The mipmap mode. Note: for settings other than None, the image must have mipmaps * calculated with makeCopyWithDefaultMipmaps; * @param paint */ drawImageOptions(img: Image, left: number, top: number, fm: FilterMode, mm: MipmapMode, paint: Paint | null): void; /** * Draws the current frame of the given animated image with its top-left corner at * (left, top) using the current clip, the current matrix, and optionally-provided paint. * @param aImg * @param left * @param top * @param paint */ drawImageAtCurrentFrame(aImg: AnimatedImage, left: number, top: number, paint?: Paint): void; /** * Draws the provided image stretched proportionally to fit into dst rectangle. * The center rectangle divides the image into nine sections: four sides, four corners, and * the center. * @param img * @param center * @param dest * @param filter - what technique to use when sampling the image * @param paint */ drawImageNine(img: Image, center: InputIRect, dest: InputRect, filter: FilterMode, paint?: Paint): void; /** * Draws sub-rectangle src from provided image, scaled and translated to fill dst rectangle. * @param img * @param src * @param dest * @param paint * @param fastSample - if false, will filter strictly within src. */ drawImageRect(img: Image, src: InputRect, dest: InputRect, paint: Paint, fastSample?: boolean): void; /** * Draws sub-rectangle src from provided image, scaled and translated to fill dst rectangle. * It will use the cubic sampling options B and C if necessary. * @param img * @param src * @param dest * @param B - See CubicResampler in SkSamplingOptions.h for more information * @param C - See CubicResampler in SkSamplingOptions.h for more information * @param paint */ drawImageRectCubic(img: Image, src: InputRect, dest: InputRect, B: number, C: number, paint?: Paint): void; /** * Draws sub-rectangle src from provided image, scaled and translated to fill dst rectangle. * It will use the provided sampling options if necessary. * @param img * @param src * @param dest * @param fm - The filter mode. * @param mm - The mipmap mode. Note: for settings other than None, the image must have mipmaps * calculated with makeCopyWithDefaultMipmaps; * @param paint */ drawImageRectOptions(img: Image, src: InputRect, dest: InputRect, fm: FilterMode, mm: MipmapMode, paint?: Paint): void; /** * Draws line segment from (x0, y0) to (x1, y1) using the current clip, current matrix, * and the provided paint. * @param x0 * @param y0 * @param x1 * @param y1 * @param paint */ drawLine(x0: number, y0: number, x1: number, y1: number, paint: Paint): void; /** * Draws an oval bounded by the given rectangle using the current clip, current matrix, * and the provided paint. * @param oval * @param paint */ drawOval(oval: InputRect, paint: Paint): void; /** * Fills clip with the given paint. * @param paint */ drawPaint(paint: Paint): void; /** * Draws the given Paragraph at the provided coordinates. * Requires the Paragraph code to be compiled in. * @param p * @param x * @param y */ drawParagraph(p: Paragraph, x: number, y: number): void; /** * Draws the given path using the current clip, current matrix, and the provided paint. * @param path * @param paint */ drawPath(path: Path, paint: Paint): void; /** * Draws the given picture using the current clip, current matrix, and the provided paint. * @param skp */ drawPicture(skp: SkPicture): void; /** * Draws the given points using the current clip, current matrix, and the provided paint. * * See Canvas.h for more on the mode and its interaction with paint. * @param mode * @param points * @param paint */ drawPoints(mode: PointMode, points: InputFlattenedPointArray, paint: Paint): void; /** * Draws the given rectangle using the current clip, current matrix, and the provided paint. * @param rect * @param paint */ drawRect(rect: InputRect, paint: Paint): void; /** * Draws the given rectangle using the current clip, current matrix, and the provided paint. * @param left * @param top * @param right * @param bottom * @param paint */ drawRect4f(left: number, top: number, right: number, bottom: number, paint: Paint): void; /** * Draws the given rectangle with rounded corners using the current clip, current matrix, * and the provided paint. * @param rrect * @param paint */ drawRRect(rrect: InputRRect, paint: Paint): void; /** * Draw an offset spot shadow and outlining ambient shadow for the given path using a disc * light. See SkShadowUtils.h for more details * @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 ambientColor - The color of the ambient shadow. * @param spotColor - The color of the spot shadow. * @param flags - See SkShadowFlags.h; 0 means use default options. */ drawShadow(path: Path, zPlaneParams: InputVector3, lightPos: InputVector3, lightRadius: number, ambientColor: InputColor, spotColor: InputColor, flags: number): void; /** * Draw the given text at the location (x, y) using the provided paint and font. If non-shaped * text is provided, the text will be drawn as is; no line-breaking, no ligatures, etc. * @param str - either a string or pre-shaped text. Unicode text is supported. * @param x * @param y * @param paint * @param font */ drawText(str: string | ShapedText, x: number, y: number, paint: Paint, font: Font): void; /** * Draws the given TextBlob at (x, y) using the current clip, current matrix, and the * provided paint. Reminder that the fonts used to draw TextBlob are part of the blob. * @param blob * @param x * @param y * @param paint */ drawTextBlob(blob: TextBlob, x: number, y: number, paint: Paint): void; /** * Draws the given vertices (a triangle mesh) using the current clip, current matrix, and the * provided paint. * If paint contains an Shader and vertices does not contain texCoords, the shader * is mapped using the vertices' positions. * If vertices colors are defined in vertices, and Paint paint contains Shader, * BlendMode mode combines vertices colors with Shader. * @param verts * @param mode * @param paint */ drawVertices(verts: Vertices, mode: BlendMode, paint: Paint): void; /** * Returns the 4x4 matrix matching the given marker or null if there was none. * See also markCTM. * @param marker */ findMarkedCTM(marker: string): Matrix4x4 | null; /** * Returns the current transform from local coordinates to the 'device', which for most * purposes means pixels. */ getLocalToDevice(): Matrix4x4; /** * Returns the number of saved states, each containing: Matrix and clip. * Equals the number of save() calls less the number of restore() calls plus one. * The save count of a new canvas is one. */ getSaveCount(): number; /** * Legacy version of getLocalToDevice(), which strips away any Z information, and * just returns a 3x3 version. */ getTotalMatrix(): number[]; /** * Creates Surface matching info and props, and associates it with Canvas. * Returns null if no match found. * @param info */ makeSurface(info: ImageInfo): Surface | null; /** * Record a marker (provided by caller) for the current CTM. This does not change anything * about the ctm or clip, but does "name" this matrix value, so it can be referenced by * custom effects (who access it by specifying the same name). * See also findMarkedCTM. * @param marker */ markCTM(marker: string): void; /** * Returns a TypedArray containing the pixels reading starting at (srcX, srcY) and does not * exceed the size indicated by imageInfo. See SkCanvas.h for more on the caveats. * * If dest is not provided, we allocate memory equal to the provided height * the provided * bytesPerRow to fill the data with. * * This is generally a very expensive call for the GPU backend. * * @param srcX * @param srcY * @param imageInfo - describes the destination format of the pixels. * @param dest - If provided, the pixels will be copied into the allocated buffer allowing * access to the pixels without allocating a new TypedArray. * @param bytesPerRow - number of bytes per row. Must be provided if dest is set. This * depends on destination ColorType. For example, it must be at least 4 * width for * the 8888 color type. * @returns a TypedArray appropriate for the specified ColorType. Note that 16 bit floats are * not supported in JS, so that colorType corresponds to raw bytes Uint8Array. */ readPixels(srcX: number, srcY: number, imageInfo: ImageInfo, dest?: MallocObj, bytesPerRow?: number): Uint8Array | Float32Array | null; /** * Removes changes to the current matrix and clip since Canvas state was * last saved. The state is removed from the stack. * Does nothing if the stack is empty. */ restore(): void; /** * Restores state to a previous stack value. * @param saveCount */ restoreToCount(saveCount: number): void; /** * Rotates the current matrix by the number of degrees. * @param rot - angle of rotation in degrees. * @param rx * @param ry */ rotate(rot: AngleInDegrees, rx: number, ry: number): void; /** * Saves the current matrix and clip and returns current height of the stack. */ save(): number; /**