Skip to main content

Layer API

Layer represents an individual drawable surface with its own <canvas> element, blending mode, opacity, and visibility.

import { Layer } from "fuderu";

Constructor

new Layer(options: LayerOptions);

LayerOptions

PropertyTypeDescription
id?stringUnique ID; if omitted a UUID is generated.
name?stringLayer name (defaults to "Layer").
widthnumberCanvas width in pixels.
heightnumberCanvas height in pixels.
visible?booleanWhether the layer is visible (defaults to true).
opacity?numberOpacity 0‑1 (defaults to 1).
blendMode?BlendModeComposite operation (defaults to "source-over").

Properties

PropertyTypeDescription
idstring (readonly)Unique identifier.
namestringHuman‑readable name.
canvasHTMLCanvasElement (readonly)The underlying canvas element.
ctxCanvasRenderingContext2D (readonly)2D rendering context of the canvas.
visiblebooleanToggles layer visibility during composition.
opacitynumber (0‑1)Opacity applied when the layer is composited.
blendModeBlendModeComposite operation used when drawing the layer onto the canvas below.

Methods

clear(): void

Clears the entire canvas (ctx.clearRect(0,0,width,height)).

resize(width: number, height: number): void

Resizes the internal canvas while preserving existing content via getImageData/putImageData.

setOpacity(opacity: number): void

Sets the layer’s opacity, clamping the value to the range [0, 1].

Usage Example

import { Layer } from "fuderu";

// Create a layer 512×512, named "Line Art", with 50% opacity and multiply blend
const lineArt = new Layer({
name: "Line Art",
width: 512,
height: 512,
opacity: 0.5,
blendMode: "multiply",
});

// Draw into the layer
const ctx = lineArt.ctx;
ctx.fillStyle = "#ff0000";
ctx.fillRect(50, 50, 200, 200);

// Later, change blend mode
lineArt.blendMode = "overlay";

// Resize the layer (e.g., when the canvas size changes)
lineArt.resize(1024, 1024);