Skip to main content

@twick/canvas - v0.14.0

Table of contents

Functions

Type Aliases

Variables

Functions

addTextElement

addTextElement(«destructured»): FabricText<{ left: Position = x; top: Position = y; originX: "center" = "center"; originY: "center" = "center"; angle: number ; fontSize: number ; fontFamily: string ; fontStyle: string ; fontWeight: string ; fill: string ; opacity: number ; skipWrapping: boolean = false; textAlign: "left" | "center" | "right" ; stroke: string ; strokeWidth: number ; shadow: undefined | Shadow }, SerializedTextProps, ObjectEvents>

Add a text element to the canvas. Creates and configures a Fabric.js text object with specified properties including position, styling, and interactive controls.

Parameters

NameType
«destructured»Object
› elementCanvasElement
› indexnumber
› canvasCanvas
› canvasMetadataCanvasMetadata

Returns

FabricText<{ left: Position = x; top: Position = y; originX: "center" = "center"; originY: "center" = "center"; angle: number ; fontSize: number ; fontFamily: string ; fontStyle: string ; fontWeight: string ; fill: string ; opacity: number ; skipWrapping: boolean = false; textAlign: "left" | "center" | "right" ; stroke: string ; strokeWidth: number ; shadow: undefined | Shadow }, SerializedTextProps, ObjectEvents>

The configured Fabric.js text object

Example

const textElement = addTextElement({
element: { id: "text1", props: { text: "Hello", x: 100, y: 100 } },
index: 1,
canvas: fabricCanvas,
canvasMetadata: { scaleX: 1, scaleY: 1, width: 800, height: 600 }
});

Defined in

components/elements.tsx:44


addCaptionElement

addCaptionElement(«destructured»): FabricText<{ left: Position = x; top: Position = y; originX: "center" = "center"; originY: "center" = "center"; angle: number ; fontSize: number ; fontFamily: string ; fill: string ; fontWeight: number = DEFAULT_CAPTION_PROPS.fontWeight; stroke: string ; opacity: number ; shadow: Shadow ; strokeWidth: number }, SerializedTextProps, ObjectEvents>

Add a caption element to the canvas based on provided props. Creates a text element with caption-specific styling including shadows, positioning, and font properties.

Parameters

NameType
«destructured»Object
› elementCanvasElement
› indexnumber
› canvasCanvas
› captionPropsCaptionProps
› canvasMetadataCanvasMetadata

Returns

FabricText<{ left: Position = x; top: Position = y; originX: "center" = "center"; originY: "center" = "center"; angle: number ; fontSize: number ; fontFamily: string ; fill: string ; fontWeight: number = DEFAULT_CAPTION_PROPS.fontWeight; stroke: string ; opacity: number ; shadow: Shadow ; strokeWidth: number }, SerializedTextProps, ObjectEvents>

The configured Fabric.js caption object

Example

const captionElement = addCaptionElement({
element: { id: "caption1", props: { text: "Caption", pos: { x: 100, y: 100 } } },
index: 3,
canvas: fabricCanvas,
captionProps: { font: { size: 24, family: "Arial" } },
canvasMetadata: { scaleX: 1, scaleY: 1, width: 800, height: 600 }
});

Defined in

components/elements.tsx:194


addVideoElement

addVideoElement(«destructured»): Promise<undefined | FabricImage<Partial<ImageProps>, SerializedImageProps, ObjectEvents> | Group>

Add a video frame as element into a Fabric.js image object and optionally groups it with a frame. Creates a video element by extracting a frame at the specified time and applying optional frame effects for enhanced visual presentation.

Parameters

NameType
«destructured»Object
› elementCanvasElement
› indexnumber
› canvasCanvas
› snapTimenumber
› canvasMetadataCanvasMetadata
› currentFrameEffect?FrameEffect

Returns

Promise<undefined | FabricImage<Partial<ImageProps>, SerializedImageProps, ObjectEvents> | Group>

A Fabric.js image object or a group with an image and frame

Example

const videoElement = await addVideoElement({
element: {
id: "video1",
props: { src: "video.mp4", x: 100, y: 100 }
},
index: 2,
canvas: fabricCanvas,
snapTime: 5.0,
canvasMetadata: { scaleX: 1, scaleY: 1, width: 800, height: 600 },
currentFrameEffect: { shape: "circle", radius: 50 }
});

Defined in

components/elements.tsx:295


addImageElement

addImageElement(«destructured»): Promise<undefined | FabricImage<Partial<ImageProps>, SerializedImageProps, ObjectEvents> | Group>

Add an image element to the canvas and optionally group it with a frame. Loads an image from URL and creates a Fabric.js image object with proper positioning, scaling, and optional frame effects.

Parameters

NameType
«destructured»Object
› imageUrl?string
› elementCanvasElement
› indexnumber
› canvasCanvas
› canvasMetadataCanvasMetadata
› currentFrameEffect?FrameEffect

Returns

Promise<undefined | FabricImage<Partial<ImageProps>, SerializedImageProps, ObjectEvents> | Group>

A Fabric.js image object or a group with an image and frame

Example

const imageElement = await addImageElement({
imageUrl: "https://example.com/image.jpg",
element: { id: "img1", props: { src: "image.jpg", width: 200, height: 150 } },
index: 4,
canvas: fabricCanvas,
canvasMetadata: { scaleX: 1, scaleY: 1, width: 800, height: 600 }
});

Defined in

components/elements.tsx:357


addRectElement

addRectElement(«destructured»): Rect<{ left: Position = x; top: Position = y; originX: "center" = "center"; originY: "center" = "center"; angle: number ; rx: number ; ry: number ; stroke: string ; strokeWidth: number ; fill: string ; opacity: number ; width: number ; height: number }, SerializedRectProps, ObjectEvents>

Add a rectangular element to the canvas. Creates a Fabric.js rectangle with specified properties including position, size, styling, and interactive controls.

Parameters

NameType
«destructured»Object
› elementCanvasElement
› indexnumber
› canvasCanvas
› canvasMetadataCanvasMetadata

Returns

Rect<{ left: Position = x; top: Position = y; originX: "center" = "center"; originY: "center" = "center"; angle: number ; rx: number ; ry: number ; stroke: string ; strokeWidth: number ; fill: string ; opacity: number ; width: number ; height: number }, SerializedRectProps, ObjectEvents>

A Fabric.js Rect object configured with the specified properties

Example

const rectElement = addRectElement({
element: { id: "rect1", props: { width: 100, height: 50, x: 200, y: 150 } },
index: 6,
canvas: fabricCanvas,
canvasMetadata: { scaleX: 1, scaleY: 1, width: 800, height: 600 }
});

Defined in

components/elements.tsx:575


addBackgroundColor

addBackgroundColor(«destructured»): Rect<{ width: number = canvasMetadata.width; height: number = canvasMetadata.height; left: number ; top: number ; fill: string ; originX: "center" = "center"; originY: "center" = "center"; hasControls: false = false; hasBorders: false = false; selectable: false = false }, SerializedRectProps, ObjectEvents>

Add a background color to the canvas. Creates a full-canvas rectangle with the specified background color that serves as the base layer for other elements.

Parameters

NameType
«destructured»Object
› elementCanvasElement
› indexnumber
› canvasCanvas
› canvasMetadataCanvasMetadata

Returns

Rect<{ width: number = canvasMetadata.width; height: number = canvasMetadata.height; left: number ; top: number ; fill: string ; originX: "center" = "center"; originY: "center" = "center"; hasControls: false = false; hasBorders: false = false; selectable: false = false }, SerializedRectProps, ObjectEvents>

A Fabric.js Rect object configured with the specified properties

Example

const bgElement = addBackgroundColor({
element: { id: "bg1", backgoundColor: "#ffffff" },
index: 0,
canvas: fabricCanvas,
canvasMetadata: { scaleX: 1, scaleY: 1, width: 800, height: 600 }
});

Defined in

components/elements.tsx:642


createCanvas

createCanvas(«destructured»): Object

Creates and initializes a Fabric.js canvas with specified configurations. Sets up a canvas with proper scaling, background, and interaction settings based on the provided video and canvas dimensions.

Parameters

NameType
«destructured»CanvasProps

Returns

Object

Object containing the initialized canvas and its metadata

NameType
canvasCanvas
canvasMetadataCanvasMetadata

Example

const { canvas, canvasMetadata } = createCanvas({
videoSize: { width: 1920, height: 1080 },
canvasSize: { width: 800, height: 600 },
canvasRef: canvasElement,
backgroundColor: "#000000",
selectionBorderColor: "#2563eb"
});

Defined in

helpers/canvas.util.ts:33


reorderElementsByZIndex

reorderElementsByZIndex(canvas): void

Reorders elements on the canvas based on their zIndex property. Sorts all canvas objects by their zIndex and re-adds them to maintain proper layering order for visual elements.

Parameters

NameTypeDescription
canvasCanvasThe Fabric.js canvas instance

Returns

void

Example

reorderElementsByZIndex(canvas);
// Elements are now properly layered based on zIndex

Defined in

helpers/canvas.util.ts:102


convertToCanvasPosition

convertToCanvasPosition(x, y, canvasMetadata): Position

Converts a position from the video coordinate space to the canvas coordinate space. Applies scaling and centering transformations to map video coordinates to the corresponding canvas pixel positions.

Parameters

NameTypeDescription
xnumberX-coordinate in video space
ynumberY-coordinate in video space
canvasMetadataCanvasMetadataMetadata containing canvas scaling and dimensions

Returns

Position

Object containing the corresponding position in canvas space

Example

const canvasPos = convertToCanvasPosition(100, 200, canvasMetadata);
// canvasPos = { x: 450, y: 500 }

Defined in

helpers/canvas.util.ts:168


convertToVideoPosition

convertToVideoPosition(x, y, canvasMetadata, videoSize): Position

Converts a position from the canvas coordinate space to the video coordinate space. Applies inverse scaling and centering transformations to map canvas coordinates back to the corresponding video coordinate positions.

Parameters

NameTypeDescription
xnumberX-coordinate in canvas space
ynumberY-coordinate in canvas space
canvasMetadataCanvasMetadataMetadata containing canvas scaling and dimensions
videoSizeDimensionsDimensions of the video

Returns

Position

Object containing the corresponding position in video space

Example

const videoPos = convertToVideoPosition(450, 500, canvasMetadata, videoSize);
// videoPos = { x: 100, y: 200 }

Defined in

helpers/canvas.util.ts:196


getCurrentFrameEffect

getCurrentFrameEffect(item, seekTime): any

Retrieves the current frame effect for a given seek time. Searches through the item's frame effects to find the one that is active at the specified seek time based on start and end time ranges.

Parameters

NameTypeDescription
itemanyThe item containing frame effects
seekTimenumberThe current time to match against frame effects

Returns

any

The current frame effect active at the given seek time, or undefined if none found

Example

const currentEffect = getCurrentFrameEffect(videoElement, 5.5);
// Returns the frame effect active at 5.5 seconds, if any

Defined in

helpers/canvas.util.ts:223


useTwickCanvas

useTwickCanvas(«destructured»): Object

Custom hook to manage a Fabric.js canvas and associated operations. Provides functionality for canvas initialization, element management, and event handling for interactive canvas operations.

Parameters

NameType
«destructured»Object
› onCanvasReady?(canvas: Canvas) => void
› onCanvasOperation?(operation: string, data: any) => void

Returns

Object

Object containing canvas-related functions and state

NameType
twickCanvasnull | Canvas
buildCanvas(props: CanvasProps & { forceBuild?: boolean }) => void
onVideoSizeChange(videoSize: Dimensions) => void
addElementToCanvas(options: { element: CanvasElement ; index: number ; reorder: boolean = true; seekTime?: number ; captionProps?: any }) => Promise<void>
setCanvasElements(options: { elements: CanvasElement[] ; seekTime?: number = 0; captionProps?: any ; cleanAndAdd?: boolean = false }) => Promise<void>

Example

const { twickCanvas, buildCanvas, addElementToCanvas } = useTwickCanvas({
onCanvasReady: (canvas) => console.log('Canvas ready:', canvas),
onCanvasOperation: (operation, data) => console.log('Operation:', operation, data)
});

Defined in

hooks/use-twick-canvas.ts:40

Type Aliases

CanvasProps

Ƭ CanvasProps: Object

Configuration properties for creating and initializing a canvas. Defines the video and canvas dimensions, styling options, and interaction settings.

Example

const canvasProps: CanvasProps = {
videoSize: { width: 1920, height: 1080 },
canvasSize: { width: 800, height: 600 },
canvasRef: canvasElement,
backgroundColor: "#000000",
selectionBorderColor: "#2563eb",
selectionLineWidth: 2,
uniScaleTransform: true,
enableRetinaScaling: true,
touchZoomThreshold: 10
};

Type declaration

NameTypeDescription
videoSizeDimensionsDimensions of the video content
canvasSizeDimensionsDimensions of the canvas element
canvasRefHTMLCanvasElement | stringReference to the HTML canvas element or selector string
backgroundColor?stringBackground color of the canvas
selectionBorderColor?stringBorder color for selected objects
selectionLineWidth?numberWidth of the selection border
uniScaleTransform?booleanEnsures uniform scaling of objects
enableRetinaScaling?booleanEnables retina scaling for higher DPI displays
touchZoomThreshold?numberThreshold for touch zoom interactions

Defined in

types.ts:28


CanvasMetadata

Ƭ CanvasMetadata: Object

Metadata about the canvas including dimensions and scaling factors. Contains calculated values for coordinate transformations between video and canvas spaces.

Example

const metadata: CanvasMetadata = {
width: 800,
height: 600,
aspectRatio: 1.33,
scaleX: 0.416,
scaleY: 0.556
};

Type declaration

NameTypeDescription
widthnumberWidth of the canvas in pixels
heightnumberHeight of the canvas in pixels
aspectRationumberAspect ratio of the canvas (width / height)
scaleXnumberHorizontal scaling factor from video to canvas
scaleYnumberVertical scaling factor from video to canvas

Defined in

types.ts:64


FrameEffect

Ƭ FrameEffect: Object

Frame effect configuration for canvas elements. Defines visual effects that can be applied to elements during specific time ranges.

Example

const frameEffect: FrameEffect = {
s: 0,
e: 5,
props: {
shape: "circle",
radius: 50,
rotation: 45,
framePosition: { x: 100, y: 100 },
frameSize: [200, 200]
}
};

Type declaration

NameTypeDescription
snumberStart time of the effect in seconds
enumberEnd time of the effect in seconds
props{ shape?: "circle" | "rect" ; radius?: number ; rotation?: number ; framePosition?: { x: number ; y: number } ; frameSize?: [number, number] }Effect properties and configuration
props.shape?"circle" | "rect"Shape type for the frame effect
props.radius?numberRadius for circular effects
props.rotation?numberRotation angle in degrees
props.framePosition?{ x: number ; y: number }Position of the frame effect
props.framePosition.xnumberX coordinate
props.framePosition.ynumberY coordinate
props.frameSize?[number, number]Size of the frame effect [width, height]

Defined in

types.ts:96


CanvasElement

Ƭ CanvasElement: Object

Canvas element configuration for various element types. Defines the structure for text, image, video, and other elements on the canvas.

Example

const canvasElement: CanvasElement = {
id: "element-1",
type: "text",
props: {
text: "Hello World",
x: 100,
y: 100,
fontSize: 48
},
s: 0,
e: 10,
frameEffects: [frameEffect]
};

Type declaration

NameTypeDescription
idstringUnique identifier for the element
typestringType of element (text, image, video, etc.)
propsCanvasElementPropsElement properties and styling
s?numberStart time of the element in seconds
e?numberEnd time of the element in seconds
t?stringText content for text elements
frameEffects?FrameEffect[]Array of frame effects applied to the element
timelineType?stringType of timeline element
backgoundColor?stringBackground color for the element
objectFit?"contain" | "cover" | "fill" | "none"Object fit mode for media elements
frame?{ size?: [number, number] ; rotation?: number ; scaleX?: number ; scaleY?: number ; stroke?: string ; lineWidth?: number ; radius?: number ; x: number ; y: number }Frame configuration for the element
frame.size?[number, number]Size of the frame [width, height]
frame.rotation?numberRotation angle in degrees
frame.scaleX?numberHorizontal scale factor
frame.scaleY?numberVertical scale factor
frame.stroke?stringStroke color
frame.lineWidth?numberStroke line width
frame.radius?numberCorner radius for rounded rectangles
frame.xnumberX coordinate
frame.ynumberY coordinate

Defined in

types.ts:142


CanvasElementProps

Ƭ CanvasElementProps: Object

Properties for canvas elements including styling, positioning, and media attributes. Comprehensive type definition covering all possible element properties.

Example

const elementProps: CanvasElementProps = {
src: "image.jpg",
text: "Sample Text",
x: 100,
y: 100,
rotation: 45,
scaleX: 1.5,
scaleY: 1.5,
opacity: 0.8,
fontSize: 48,
fontFamily: "Arial",
fill: "#FFFFFF",
stroke: "#000000"
};

Type declaration

NameTypeDescription
src?stringSource URL for media elements
text?stringText content for text elements
rotation?numberRotation angle in degrees
scaleX?numberHorizontal scale factor
scaleY?numberVertical scale factor
size?[number, number]Size array [width, height]
x?numberX coordinate position
y?numberY coordinate position
radius?numberCorner radius for rounded shapes
opacity?numberOpacity value (0-1)
width?numberWidth in pixels
height?numberHeight in pixels
textWrap?booleanWhether text should wrap
textAlign?"left" | "center" | "right"Text alignment
pos?{ x: number ; y: number }Position object with x, y coordinates
pos.xnumberX coordinate
pos.ynumberY coordinate
shadow?{ color: string ; blur: number ; offsetX: number ; offsetY?: number }Shadow configuration
shadow.colorstringShadow color
shadow.blurnumberShadow blur radius
shadow.offsetXnumberShadow X offset
shadow.offsetY?numberShadow Y offset
font?{ family?: string ; size?: number ; style?: string ; weight?: string }Font configuration object
font.family?stringFont family
font.size?numberFont size in pixels
font.style?stringFont style
font.weight?stringFont weight
fontFamily?stringFont family name
fontSize?numberFont size in pixels
fontStyle?stringFont style (normal, italic, etc.)
fontWeight?stringFont weight (normal, bold, etc.)
fill?stringFill color
stroke?stringStroke color
strokeWidth?numberStroke width
lineWidth?numberLine width for strokes
shadowColor?stringShadow color
shadowBlur?numberShadow blur radius
shadowOffset?[number, number]Shadow offset [x, y]
playbackRate?numberPlayback rate for video elements
time?numberCurrent time for video elements

Defined in

types.ts:208


CaptionProps

Ƭ CaptionProps: Object

Properties specific to caption elements. Defines styling and positioning for caption text with background and highlight options.

Example

const captionProps: CaptionProps = {
font: {
family: "Arial",
size: 48,
fill: "#FFFFFF"
},
pos: {
x: 100,
y: 100
},
color: {
text: "#FFFFFF",
background: "#000000",
highlight: "#FFFF00"
}
};

Type declaration

NameTypeDescription
font?{ family?: string ; size?: number ; fill?: string }Font configuration for caption text
font.family?stringFont family
font.size?numberFont size in pixels
font.fill?stringText fill color
pos?{ x: number ; y: number }Position of the caption
pos.xnumberX coordinate
pos.ynumberY coordinate
color?{ text?: string ; background?: string ; highlight?: string }Color configuration for caption styling
color.text?stringText color
color.background?stringBackground color
color.highlight?stringHighlight color

Defined in

types.ts:318

Variables

disabledControl

Const disabledControl: Control

Disabled control for canvas elements. Creates a control that appears disabled and doesn't perform any actions when interacted with. Useful for showing non-interactive control points.

Example

import { disabledControl } from '@twick/canvas';

// Apply to a canvas object
object.setControlsVisibility({
mt: false, // Disable top control
mb: false, // Disable bottom control
ml: false, // Disable left control
mr: false, // Disable right control
bl: disabledControl, // Use disabled control for bottom-left
});

Defined in

components/element-controls.tsx:22


rotateControl

Const rotateControl: Control

Rotation control for canvas elements. Creates a control that allows rotation of canvas objects with snapping functionality for precise angle adjustments.

Example

import { rotateControl } from '@twick/canvas';

// Apply to a canvas object
object.setControlsVisibility({
mtr: rotateControl, // Use custom rotate control for top-right
});

// Enable rotation
object.set({
hasRotatingPoint: true,
lockRotation: false
});

Defined in

components/element-controls.tsx:71


CANVAS_OPERATIONS

Const CANVAS_OPERATIONS: Object

Canvas operation constants for tracking canvas state changes. Defines the different types of operations that can occur on canvas elements.

Example

import { CANVAS_OPERATIONS } from '@twick/canvas';

function handleCanvasOperation(operation) {
switch (operation) {
case CANVAS_OPERATIONS.ITEM_ADDED:
console.log('New item added to canvas');
break;
case CANVAS_OPERATIONS.ITEM_UPDATED:
console.log('Item updated on canvas');
break;
}
}

Type declaration

NameTypeDescription
ITEM_SELECTEDstringAn item has been selected on the canvas
ITEM_UPDATEDstringAn item has been updated/modified on the canvas
ITEM_DELETEDstringAn item has been deleted from the canvas
ITEM_ADDEDstringA new item has been added to the canvas
ITEM_GROUPEDstringItems have been grouped together
ITEM_UNGROUPEDstringItems have been ungrouped

Defined in

helpers/constants.ts:97