ThorVG WebCanvas API - v1.1.4
    Preparing search index...

    Class Shape

    Shape class for creating and manipulating vector graphics paths.

    Extends Paint to inherit transformation and opacity methods.

    // Drawing basic shapes
    const shape = new TVG.Shape();

    // Rectangle with rounded corners
    shape.appendRect(50, 50, 200, 100, 10)
    .fill(255, 100, 100, 255)
    .stroke(50, 50, 50, 255, 2);

    canvas.add(shape);
    // Drawing paths with gradients
    const shape = new TVG.Shape();
    shape.moveTo(100, 100)
    .lineTo(200, 150)
    .lineTo(150, 250)
    .close();

    const gradient = new TVG.LinearGradient(100, 100, 200, 250);
    gradient.addStop(0, [255, 0, 0, 255])
    .addStop(1, [0, 0, 255, 255]);

    shape.fillGradient(gradient);
    canvas.add(shape);
    // Complex path with transformations
    const shape = new TVG.Shape();
    shape.appendCircle(0, 0, 50)
    .fill(100, 200, 255, 255)
    .translate(400, 300)
    .scale(1.5)
    .rotate(45);

    canvas.add(shape);

    Hierarchy (View Summary)

    Index
    • get id(): number

      The ID of this paint object. IDs are used to identify paint objects within a picture's scene tree. Assign a string to generate a hash ID from the name, or a number to set directly.

      Returns number

    • set id(value: string | number): void

      Parameters

      • value: string | number

      Returns void

    • get ptr(): number

      Gets the WASM pointer for this object Returns 0 if object has been disposed (error handled by global handler)

      Returns number

    • get isDisposed(): boolean

      Check if this object has been disposed

      Returns boolean

    • Cleanup function to be implemented by subclasses

      Parameters

      • ptr: number

        The WASM pointer to clean up

      Returns void

    • Translate the paint by (x, y)

      Parameters

      • x: number
      • y: number

      Returns this

    • Rotate the paint by angle (in degrees)

      Parameters

      • angle: number

      Returns this

    • Scale the paint by factor

      Parameters

      • factor: number

      Returns this

    • Set the blending method for this paint. Blending determines how this paint is combined with the content below it.

      Parameters

      Returns this

      The Paint instance for method chaining

      const scene = new TVG.Scene();
      scene.blend(BlendMethod.Add);

      const shape = new TVG.Shape();
      shape.appendCircle(100, 100, 50, 50);
      shape.fill(255, 0, 0, 255);
      shape.blend(BlendMethod.Multiply);
    • Get or set the opacity (0 to 255)

      Returns number

      When setting, returns the Paint instance for method chaining. When getting, returns the opacity value (0-255).

      // Set opacity to 50% (half transparent)
      shape.opacity(128);

      // Set to fully opaque
      shape.opacity(255);

      // Get current opacity value
      const currentOpacity = shape.opacity(); // returns 0-255
    • Get or set the opacity (0 to 255)

      Parameters

      • value: number

        The opacity value in the range [0 ~ 255], where 0 is completely transparent and 255 is opaque.

      Returns this

      When setting, returns the Paint instance for method chaining. When getting, returns the opacity value (0-255).

      // Set opacity to 50% (half transparent)
      shape.opacity(128);

      // Set to fully opaque
      shape.opacity(255);

      // Get current opacity value
      const currentOpacity = shape.opacity(); // returns 0-255
    • Get the axis-aligned bounding box (AABB) of this paint

      Returns Bounds

    • Get the oriented bounding box (OBB) of this paint as 4 corner points

      Parameters

      • options: { oriented: true }

        Options object with oriented flag

      Returns Point[]

    • Duplicates the object.

      Creates a new object and sets its all properties as in the original object.

      Type Parameters

      • T extends Paint

        The Paint subclass type of the created object

      Returns T

      The created object

    • Applies a custom transformation matrix to the paint.

      This method allows you to apply complex transformations that combine translation, rotation, scaling, and skewing in a single operation. The matrix is multiplied with any existing transformations.

      Parameters

      • matrix: Matrix

        A 3x3 transformation matrix

      Returns this

      The Paint instance for method chaining

      // Apply a combined transformation
      const shape = new TVG.Shape();
      shape.appendRect(0, 0, 100, 100);

      // Create a matrix for: scale(2, 1.5) + rotate(45deg) + translate(100, 50)
      const rad = (45 * Math.PI) / 180;
      const cos = Math.cos(rad);
      const sin = Math.sin(rad);

      shape.transform({
      e11: 2 * cos, e12: -2 * sin, e13: 100,
      e21: 1.5 * sin, e22: 1.5 * cos, e23: 50,
      e31: 0, e32: 0, e33: 1
      });
      // Create a skew transformation
      const shape = new TVG.Shape();
      shape.appendRect(0, 0, 100, 100);

      // Skew in X direction
      shape.transform({
      e11: 1, e12: 0.5, e13: 0,
      e21: 0, e22: 1, e23: 0,
      e31: 0, e32: 0, e33: 1
      });
    • Sets a clipping path for this paint object.

      The clipping path restricts the area where the paint will be rendered. Only the parts of the paint that overlap with the clipper shape will be visible.

      Parameters

      • clipper: Paint

        A Paint object (typically a Shape) to use as the clipping path

      Returns this

      The Paint instance for method chaining

      const circle = new TVG.Shape();
      circle.appendCircle(150, 150, 100);

      const rect = new TVG.Shape();
      rect.appendRect(0, 0, 300, 300)
      .fill(255, 0, 0, 255)
      .clip(circle);

      canvas.add(rect);
    • Sets a masking target object and the masking method.

      The masking restricts the transparency of the source paint using the target paint.

      Parameters

      • target: Paint

        A Paint object to use as the masking target

      • method: MaskMethod

        The method used to mask the source object with the target

      Returns this

      The Paint instance for method chaining

      const mask = new TVG.Shape();
      mask.appendCircle(200, 200, 125);
      mask.fill(255, 255, 255);

      const shape = new TVG.Shape();
      shape.appendRect(0, 0, 400, 400)
      .fill(255, 0, 0, 255)
      .mask(mask, MaskMethod.Alpha);

      canvas.add(shape);
    • Checks whether the given rectangular region intersects the filled area of the paint.

      Useful for hit-testing, such as detecting whether a click or touch landed on a painted region. The paint must have been updated by a Canvas beforehand — typically after the canvas has been drawn and synchronized.

      Parameters

      • x: number

        The x-coordinate of the region's top-left corner

      • y: number

        The y-coordinate of the region's top-left corner

      • width: number

        The width of the region. Must be greater than 0

      • height: number

        The height of the region. Must be greater than 0

      • visibleOnly: boolean = false

        If true, hidden paints are excluded from the test (default: false)

      Returns boolean

      true if any part of the region intersects the filled area, false otherwise

      To test a single point, set width and height to 1. This test does not account for the results of blending or masking.

      visible

      const shape = new TVG.Shape();
      shape.appendRect(100, 100, 200, 200);
      canvas.add(shape).render();

      // Check if shape intersects with a region
      if (shape.intersects(150, 150, 100, 100)) {
      console.log('Shape intersects with region');
      }

      // Hit-test a single point, ignoring hidden paints
      if (shape.intersects(event.offsetX, event.offsetY, 1, 1, true)) {
      console.log('Clicked a visible part of the shape');
      }
    • Moves the path cursor to a new point without drawing.

      This starts a new subpath at the specified coordinates. Subsequent drawing commands will start from this point.

      Parameters

      • x: number

        X coordinate

      • y: number

        Y coordinate

      Returns this

      The Shape instance for method chaining

      shape.moveTo(100, 100)
      .lineTo(200, 200);
    • Draws a straight line from the current point to the specified coordinates.

      Parameters

      • x: number

        End X coordinate

      • y: number

        End Y coordinate

      Returns this

      The Shape instance for method chaining

      // Draw a triangle
      shape.moveTo(100, 50)
      .lineTo(150, 150)
      .lineTo(50, 150)
      .close();
    • Draws a cubic Bézier curve from the current point to (x, y).

      Parameters

      • cx1: number

        X coordinate of first control point

      • cy1: number

        Y coordinate of first control point

      • cx2: number

        X coordinate of second control point

      • cy2: number

        Y coordinate of second control point

      • x: number

        End X coordinate

      • y: number

        End Y coordinate

      Returns this

      The Shape instance for method chaining

      // Draw a smooth curve
      shape.moveTo(50, 100)
      .cubicTo(50, 50, 150, 50, 150, 100);
    • Closes the current subpath by drawing a straight line back to the starting point.

      Returns this

      The Shape instance for method chaining

      shape.moveTo(100, 50)
      .lineTo(150, 150)
      .lineTo(50, 150)
      .close(); // Completes the triangle
    • Appends a rectangle path to the shape.

      Creates a rectangular path with optional rounded corners. Multiple rectangles can be added to the same shape.

      Parameters

      • x: number

        X coordinate of the top-left corner

      • y: number

        Y coordinate of the top-left corner

      • w: number

        Width of the rectangle

      • h: number

        Height of the rectangle

      • options: RectOptions = {}

        Optional corner rounding and path direction

      Returns this

      The Shape instance for method chaining

      // Simple rectangle
      shape.appendRect(50, 50, 200, 100);
      // Rounded rectangle
      shape.appendRect(50, 50, 200, 100, { rx: 10, ry: 10 });
    • Appends a circle or ellipse path to the shape.

      Creates a circular or elliptical path. If only one radius is provided, creates a perfect circle. If two radii are provided, creates an ellipse.

      Parameters

      • cx: number

        X coordinate of the center

      • cy: number

        Y coordinate of the center

      • rx: number

        Horizontal radius

      • ry: number = rx

        Vertical radius (defaults to rx for perfect circle)

      • clockwise: boolean = true

        Path direction. Default: true

      Returns this

      The Shape instance for method chaining

      // Perfect circle
      shape.appendCircle(150, 150, 50)
      .fill(255, 0, 0, 255);
      // Ellipse
      shape.appendCircle(150, 150, 80, 50)
      .fill(0, 100, 255, 255);
    • Appends a pre-built path to the shape from raw command and point arrays.

      This is the low-level counterpart to moveTo, lineTo, cubicTo and close. It lets you feed an entire path in a single call, which is useful when the path data already exists in command/point form (e.g. imported from another source or produced by path).

      Each command consumes points from points in order:

      The total number of points consumed by commands must equal points.length.

      Parameters

      • commands: readonly PathCommand[]

        Path commands describing the outline

      • points: readonly (readonly number[])[]

        Points as [x, y] pairs, consumed in order by the commands

      Returns this

      The Shape instance for method chaining

      // Build a triangle in one call
      shape.appendPath(
      [PathCommand.MoveTo, PathCommand.LineTo, PathCommand.LineTo, PathCommand.Close],
      [[100, 50], [150, 150], [50, 150]]
      ).fill(255, 0, 0, 255);
    • Retrieves the shape's current path as command and point arrays.

      Returns a snapshot of the path data accumulated by the path-building methods (or appendPath). The returned arrays are copies and can be safely modified and fed back into appendPath.

      Mirrors the native Shape::path() getter.

      Returns { commands: PathCommand[]; points: [number, number][] }

      An object with commands (path commands) and points ([x, y] tuples)

      const { commands, points } = shape.path();
      // Re-append the same outline to another shape
      other.appendPath(commands, points);
    • Sets the fill rule for the shape.

      The fill rule determines how the interior of a shape is calculated when the path intersects itself or when multiple subpaths overlap.

      Parameters

      • rule: FillRule

        Fill rule: 'winding' (non-zero) or 'evenodd'

      Returns this

      The Shape instance for method chaining

      const star = new TVG.Shape();
      // Draw a self-intersecting star
      star.moveTo(100, 10)
      .lineTo(40, 180)
      .lineTo(190, 60)
      .lineTo(10, 60)
      .lineTo(160, 180)
      .close()
      .fillRule(FillRule.EvenOdd) // Use even-odd rule for star shape
      .fill(255, 200, 0, 255);
    • Sets the trim of the shape along the defined path segment, controlling which part is visible.

      This method allows you to trim/cut paths, showing only a portion from the begin to end point. This is particularly useful for animations (e.g., drawing a line progressively) or creating partial shapes like arcs from circles.

      If the values exceed the 0-1 range, they wrap around (similar to angle wrapping).

      Parameters

      • begin: number

        Start of the segment to display (0.0 to 1.0, where 0 is the path start)

      • end: number

        End of the segment to display (0.0 to 1.0, where 1 is the path end)

      • simultaneous: boolean = true

        How to handle multiple paths within the shape:

        • true (default): Trimming applied simultaneously to all paths
        • false: All paths treated as one entity with combined length

      Returns this

      The Shape instance for method chaining

      // Draw half a circle (arc)
      const arc = new TVG.Shape();
      arc.appendCircle(150, 150, 100)
      .trimPath(0, 0.5) // Show only first half
      .stroke({ width: 5, color: [255, 0, 0, 255] });
      // Animated line drawing effect
      const line = new TVG.Shape();
      line.moveTo(50, 100)
      .lineTo(250, 100)
      .trimPath(0, progress) // progress from 0 to 1
      .stroke({ width: 3, color: [0, 100, 255, 255] });
      // Trim multiple paths separately
      const shape = new TVG.Shape();
      shape.appendRect(50, 50, 100, 100)
      .appendCircle(200, 100, 50)
      .trimPath(0.25, 0.75, true) // Trim each path separately
      .stroke({ width: 2, color: [0, 0, 0, 255] });
    • Sets the fill for the shape with a gradient.

      Parameters

      • gradient: Fill

        LinearGradient, RadialGradient or ConicGradient to use as fill

      Returns this

      The Shape instance for method chaining

    • Sets the fill for the shape with a solid color.

      Parameters

      • r: number

        Red component (0-255)

      • g: number

        Green component (0-255)

      • b: number

        Blue component (0-255)

      • Optionala: number

        Alpha component (0-255). Default: 255 (opaque)

      Returns this

      The Shape instance for method chaining

    • Sets the stroke width for the shape.

      Parameters

      • width: number

        Stroke width in pixels

      Returns this

      The Shape instance for method chaining

    • Sets comprehensive stroke styling options for the shape.

      Parameters

      • options: StrokeOptions

        Stroke configuration including width, color, gradient, caps, joins, and miter limit

      Returns this

      The Shape instance for method chaining

    • Sets the rendering order of the shape's stroke and fill.

      By default the fill is rendered first and the stroke on top of it. Passing true reverses this so the stroke is drawn first and the fill on top — useful when you want the fill to cover the inner half of a thick stroke.

      Parameters

      • strokeFirst: boolean

        true renders the stroke before the fill; false (default) renders the stroke on top

      Returns this

      The Shape instance for method chaining

      shape.appendCircle(150, 150, 50)
      .fill(255, 255, 255, 255)
      .stroke({ width: 20, color: [0, 0, 0, 255] })
      .order(true); // stroke under the fill
    • Resets the shape's path data while retaining fill and stroke properties.

      This method clears all path commands (moveTo, lineTo, cubicTo, appendRect, etc.) but preserves the shape's fill color, gradient, stroke settings, and transformations. This is useful for animations where you want to redraw the path while keeping the same styling.

      Returns this

      The Shape instance for method chaining

      // Animating shape changes while keeping styles
      const shape = new TVG.Shape();
      shape.appendRect(0, 0, 100, 100);
      shape.fill(255, 0, 0, 255);
      shape.stroke({ width: 5, color: [0, 0, 255, 255] });

      // Later, change the shape but keep the fill/stroke
      shape.reset();
      shape.appendCircle(50, 50, 40);
      // Still has red fill and blue stroke!