Skip to main content
Module

x/canvas/mod.ts>CanvasKit

Canvas API for Deno, ported from canvaskit-wasm (Skia).
Latest
interface CanvasKit
Re-export
import { type CanvasKit } from "https://deno.land/x/canvas@v1.4.1/mod.ts";

Properties

readonly
ImageData: ImageDataConstructor
readonly
ParagraphStyle: ParagraphStyleConstructor
readonly
ContourMeasureIter: ContourMeasureIterConstructor
readonly
Font: FontConstructor
readonly
Paint: DefaultConstructor<Paint>
readonly
PictureRecorder: DefaultConstructor<PictureRecorder>
readonly
TextStyle: TextStyleConstructor
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
Typeface: TypefaceFactory
readonly
TypefaceFontProvider: TypefaceFontProviderFactory
readonly
ColorMatrix: ColorMatrixHelpers
readonly
Matrix: Matrix3x3Helpers
readonly
M44: Matrix4x4Helpers
readonly
Vector: VectorHelpers
readonly
AlphaType: AlphaTypeEnumValues
readonly
BlendMode: BlendModeEnumValues
readonly
BlurStyle: BlurStyleEnumValues
readonly
ClipOp: ClipOpEnumValues
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
PathOp: PathOpEnumValues
readonly
PointMode: PointModeEnumValues
readonly
ColorSpace: ColorSpaceEnumValues
readonly
StrokeCap: StrokeCapEnumValues
readonly
StrokeJoin: StrokeJoinEnumValues
readonly
TileMode: TileModeEnumValues
readonly
VertexMode: VertexModeEnumValues
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
readonly
ShadowTransparentOccluder: number

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
ShadowGeometricOnly: number

Use this shadow flag to not use analytic shadows.

readonly
ShadowDirectionalLight: number

Use this shadow flag to indicate the light position represents a direction and light radius is blur radius at elevation 1.

readonly
optional
gpu: boolean
readonly
optional
managed_skottie: boolean
readonly
optional
particles: boolean
readonly
optional
rt_effect: boolean
readonly
optional
skottie: boolean
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
readonly
NoDecoration: number
readonly
UnderlineDecoration: number
readonly
OverlineDecoration: number
readonly
LineThroughDecoration: number

Methods

Color(
r: number,
g: number,
b: number,
a?: number,
): Color

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().

Color4f(
r: number,
g: number,
b: number,
a?: number,
): Color

Construct a 4-float color. Float values are typically between 0.0 and 1.0.

ColorAsInt(
r: number,
g: number,
b: number,
a?: number,
): ColorInt

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.

getColorComponents(c: Color): number[]

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.

parseColorString(color: string, colorMap?: Record<string, Color>): Color

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.

multiplyByAlpha(c: Color, alpha: number): 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.

computeTonalColors(colors: TonalColorsInput): TonalColorsOutput

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).

LTRBRect(
left: number,
top: number,
right: number,
bottom: number,
): Rect

Returns a rectangle with the given paramaters. See Rect.h for more.

XYWHRect(
x: number,
y: number,
width: number,
height: number,
): Rect

Returns a rectangle with the given paramaters. See Rect.h for more.

LTRBiRect(
left: number,
top: number,
right: number,
bottom: number,
): IRect

Returns a rectangle with the given integer paramaters. See Rect.h for more.

XYWHiRect(
x: number,
y: number,
width: number,
height: number,
): IRect

Returns a rectangle with the given paramaters. See Rect.h for more.

RRectXY(
rect: InputRect,
rx: number,
ry: number,
): RRect

Returns a rectangle with rounded corners consisting of the given rectangle and the same radiusX and radiusY for all four corners.

getShadowLocalBounds(
path: Path,
zPlaneParams: InputVector3,
lightPos: InputVector3,
lightRadius: number,
flags: number,
dstRect?: Rect,
): Rect | null

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.

Malloc(typedArray: TypedArrayConstructor, len: number): MallocObj

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);

MallocGlyphIDs(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.

Free(m: MallocObj): void

Free frees the memory returned by Malloc. Any memory allocated by CanvasKit.Malloc needs to be released with CanvasKit.Free.

MakeCanvasSurface(canvas: HTMLCanvasElement | string): Surface | null

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.

MakeRasterDirectSurface(
pixels: MallocObj,
bytesPerRow: number,
): 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.

MakeSWCanvasSurface(canvas: HTMLCanvasElement | string): Surface | null

Creates a CPU backed (aka raster) surface.

MakeWebGLCanvasSurface(
canvas: HTMLCanvasElement | string,
colorSpace?: ColorSpace,
opts?: WebGLOptions,
): 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.

MakeSurface(width: number, height: number): 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.

GetWebGLContext(canvas: HTMLCanvasElement, opts?: WebGLOptions): WebGLContextHandle

Creates a WebGL Context from the given canvas with the given options. If options are omitted, sensible defaults will be used.

MakeGrContext(ctx: WebGLContextHandle): GrDirectContext | null

Creates a GrDirectContext from the given WebGL Context.

MakeOnScreenGLSurface(
width: number,
height: number,
colorSpace: ColorSpace,
): Surface | null

Creates a Surface that will be drawn to the given GrDirectContext (and show up on screen).

MakeRenderTarget(
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.

MakeRenderTarget(ctx: GrDirectContext, info: ImageInfo): Surface | null

Returns a (non-visible) Surface on the GPU. It has the settings provided by image info. See Surface.h for more details.

deleteContext(ctx: WebGLContextHandle): void

Deletes the associated WebGLContext. Function not available on the CPU version.

getDecodeCacheLimitBytes(): number

Returns the max size of the global cache for bitmaps used by CanvasKit.

getDecodeCacheUsedBytes(): number

Returns the current size of the global cache for bitmaps used by CanvasKit.

setDecodeCacheLimitBytes(size: number): void

Sets the max size of the global cache for bitmaps used by CanvasKit.

MakeAnimatedImageFromEncoded(bytes: Uint8Array | ArrayBuffer): AnimatedImage | null

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.

MakeCanvas(width: number, height: number): EmulatedCanvas2D

Returns an emulated Canvas2D of the given size.

MakeImage(
info: ImageInfo,
bytes: number[] | Uint8Array | Uint8ClampedArray,
bytesPerRow: number,
): Image | null

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).

MakeImageFromEncoded(bytes: Uint8Array | ArrayBuffer): 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.

MakeImageFromCanvasImageSource(src: CanvasImageSource): Image

Returns an Image with the data from the provided CanvasImageSource (e.g. ). 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.

MakePicture(bytes: Uint8Array | ArrayBuffer): SkPicture | null

Returns an SkPicture which has been serialized previously to the given bytes.

MakeVertices(
mode: VertexMode,
textureCoordinates?: InputFlattenedPointArray | null,
colors?: Float32Array | ColorIntArray | null,
indices?: number[] | null,
isVolatile?: boolean,
): Vertices

Returns an Vertices based on the given positions and optional parameters. See SkVertices.h (especially the Builder) for more details.

MakeAnimation(json: string): SkottieAnimation

Returns a Skottie animation built from the provided json string. Requires that Skottie be compiled into CanvasKit.

MakeManagedAnimation(
json: string,
assets?: Record<string, ArrayBuffer>,
filterPrefix?: string,
soundMap?: SoundMap,
): ManagedSkottieAnimation

Returns a managed Skottie animation built from the provided json string and assets. Requires that Skottie be compiled into CanvasKit.

MakeParticles(json: string, assets?: Record<string, ArrayBuffer>): Particles

Returns a Particles effect built from the provided json string and assets. Requires that Particles be compiled into CanvasKit