Skip to content

API Overview

The Fabber SVG 2025 API provides powerful programmatic access to all application features, enabling automation, custom workflows, and integration with other tools.

Getting Started with the API

API Architecture

The Fabber SVG 2025 API is built on modern JavaScript standards and follows RESTful principles:

  • Document Object Model (DOM) for scene graph manipulation
  • Event-driven architecture for real-time interactions
  • Promise-based asynchronous operations
  • TypeScript definitions for enhanced development experience

Basic Setup

To start using the API, include the Fabber SVG library:

// Import the Fabber SVG API
import { FabberSVG, Document, Shape } from 'fabber-svg-api';

// Initialize a new document
const doc = new Document({
    width: 800,
    height: 600,
    units: 'px'
});

Your First API Call

Create a simple shape programmatically:

// Create a rectangle
const rect = new Rectangle({
    x: 100,
    y: 100,
    width: 200,
    height: 150,
    fill: '#3498db',
    stroke: '#2c3e50',
    strokeWidth: 2
});

// Add to document
doc.addElement(rect);

// Export as SVG
const svgString = doc.exportSVG();
console.log(svgString);

Core API Classes

Document Class

The Document class represents your entire project:

class Document {
    constructor(options) { ... }

    // Element management
    addElement(element)
    removeElement(element)
    getElementById(id)
    getElementsByType(type)

    // Document properties
    setSize(width, height)
    setBackground(color)
    setViewBox(x, y, width, height)

    // Export functions
    exportSVG(options)
    exportPNG(options)
    exportPDF(options)

    // File operations
    save(filename)
    load(data)
}

Element Classes

All drawable objects inherit from the base Element class:

// Base element
class Element {
    constructor(options) { ... }

    // Transformation
    translate(x, y)
    rotate(angle, centerX, centerY)
    scale(sx, sy)

    // Styling
    setFill(color)
    setStroke(color, width)
    setOpacity(value)

    // Properties
    getBounds()
    getCenter()
    clone()
}

// Specific shape classes
class Rectangle extends Element { ... }
class Circle extends Element { ... }
class Path extends Element { ... }
class Text extends Element { ... }
class Group extends Element { ... }

Shape Creation

Basic Shapes

Create common geometric shapes:

// Rectangle with rounded corners
const roundedRect = new Rectangle({
    x: 50, y: 50,
    width: 100, height: 80,
    rx: 10, ry: 10,
    fill: '#e74c3c'
});

// Circle
const circle = new Circle({
    cx: 200, cy: 200,
    radius: 50,
    fill: '#9b59b6',
    stroke: '#8e44ad',
    strokeWidth: 3
});

// Ellipse
const ellipse = new Ellipse({
    cx: 300, cy: 150,
    rx: 80, ry: 40,
    fill: '#f39c12'
});

Custom Paths

Create complex shapes using path commands:

const customPath = new Path({
    d: 'M 100 100 L 200 100 L 150 200 Z',
    fill: '#2ecc71',
    stroke: '#27ae60',
    strokeWidth: 2
});

// Or use the path builder
const pathBuilder = new PathBuilder()
    .moveTo(100, 100)
    .lineTo(200, 100)
    .lineTo(150, 200)
    .closePath();

const path = new Path({
    d: pathBuilder.toString(),
    fill: '#2ecc71'
});

Text Elements

Add and style text programmatically:

const text = new Text({
    x: 100,
    y: 200,
    content: 'Hello, Fabber SVG!',
    fontFamily: 'Arial',
    fontSize: 24,
    fill: '#2c3e50',
    fontWeight: 'bold'
});

// Multi-line text
const multilineText = new Text({
    x: 100,
    y: 250,
    content: 'Line 1\nLine 2\nLine 3',
    fontFamily: 'Helvetica',
    fontSize: 16,
    lineHeight: 1.4
});

Advanced Features

Gradients and Patterns

Create sophisticated fills:

// Linear gradient
const gradient = new LinearGradient({
    id: 'myGradient',
    x1: '0%', y1: '0%',
    x2: '100%', y2: '100%',
    stops: [
        { offset: '0%', color: '#ff6b6b' },
        { offset: '50%', color: '#4ecdc4' },
        { offset: '100%', color: '#45b7d1' }
    ]
});

doc.addGradient(gradient);

const gradientRect = new Rectangle({
    x: 50, y: 50,
    width: 200, height: 100,
    fill: 'url(#myGradient)'
});

Animation Support

Add animations to your elements:

// Rotate animation
const rotateAnimation = new Animation({
    target: circle,
    property: 'rotation',
    from: 0,
    to: 360,
    duration: 2000,
    easing: 'ease-in-out',
    loop: true
});

// Start animation
rotateAnimation.start();

// Fade animation
const fadeAnimation = new Animation({
    target: rect,
    property: 'opacity',
    from: 1,
    to: 0.3,
    duration: 1000,
    autoReverse: true
});

Boolean Operations

Combine shapes programmatically:

const circle1 = new Circle({ cx: 100, cy: 100, radius: 50 });
const circle2 = new Circle({ cx: 150, cy: 100, radius: 50 });

// Union operation
const union = BooleanOps.union(circle1, circle2);

// Subtract operation
const subtraction = BooleanOps.subtract(circle1, circle2);

// Intersection
const intersection = BooleanOps.intersect(circle1, circle2);

Event Handling

Document Events

Listen for document-level changes:

// Element added
doc.on('elementAdded', (element) => {
    console.log('New element added:', element.id);
});

// Document modified
doc.on('modified', () => {
    console.log('Document has been modified');
});

// Export completed
doc.on('exportComplete', (format, data) => {
    console.log(`Export to ${format} completed`);
});

Element Events

Monitor individual element interactions:

// Click events
rect.on('click', (event) => {
    console.log('Rectangle clicked at:', event.x, event.y);
});

// Property changes
rect.on('propertyChanged', (property, oldValue, newValue) => {
    console.log(`${property} changed from ${oldValue} to ${newValue}`);
});

// Transformation events
rect.on('transformed', (transformation) => {
    console.log('Element transformed:', transformation);
});

Utility Functions

Measurement and Calculation

// Distance between points
const distance = Utils.distance(point1, point2);

// Angle between points
const angle = Utils.angleBetween(point1, point2);

// Bounding box calculations
const bounds = Utils.getBounds([element1, element2, element3]);

// Point in polygon test
const isInside = Utils.pointInPolygon(point, polygon);

Color Utilities

// Color conversion
const rgb = ColorUtils.hexToRgb('#3498db');
const hsl = ColorUtils.rgbToHsl(rgb);
const hex = ColorUtils.hslToHex(hsl);

// Color manipulation
const lighter = ColorUtils.lighten('#3498db', 0.2);
const darker = ColorUtils.darken('#3498db', 0.2);
const contrasting = ColorUtils.getContrastingColor('#3498db');

Plugin Development

Creating a Plugin

Extend Fabber SVG functionality with custom plugins:

class MyCustomPlugin {
    constructor() {
        this.name = 'My Custom Plugin';
        this.version = '1.0.0';
    }

    initialize(api) {
        // Add custom tools
        api.registerTool('myTool', MyCustomTool);

        // Add menu items
        api.addMenuItem('Tools', 'My Tool', () => {
            // Tool activation logic
        });

        // Register event handlers
        api.on('documentOpened', this.onDocumentOpened.bind(this));
    }

    onDocumentOpened(doc) {
        console.log('Document opened:', doc.name);
    }
}

// Register the plugin
FabberSVG.registerPlugin(new MyCustomPlugin());

Error Handling

API Error Management

try {
    const result = await doc.exportPNG({
        width: 1920,
        height: 1080,
        quality: 0.9
    });
    console.log('Export successful');
} catch (error) {
    if (error instanceof ValidationError) {
        console.error('Validation failed:', error.message);
    } else if (error instanceof ExportError) {
        console.error('Export failed:', error.message);
    } else {
        console.error('Unexpected error:', error);
    }
}

Validation

// Validate document before operations
const validation = doc.validate();
if (!validation.isValid) {
    console.error('Document validation failed:');
    validation.errors.forEach(error => {
        console.error(`- ${error.message} (${error.element})`);
    });
}

Performance Optimization

Batch Operations

Improve performance with batch updates:

// Batch multiple operations
doc.beginBatch();

for (let i = 0; i < 1000; i++) {
    const circle = new Circle({
        cx: Math.random() * 800,
        cy: Math.random() * 600,
        radius: 5,
        fill: '#3498db'
    });
    doc.addElement(circle);
}

doc.endBatch(); // Single render update

Memory Management

// Dispose of elements when no longer needed
element.dispose();

// Clear document
doc.clear();

// Optimize document
doc.optimize(); // Removes unused gradients, patterns, etc.

Integration Examples

Web Application Integration

// Initialize in a web page
const canvas = document.getElementById('fabber-canvas');
const doc = new Document({ canvas });

// Handle user interactions
canvas.addEventListener('click', (event) => {
    const point = doc.screenToDocument(event.clientX, event.clientY);
    const element = doc.getElementAt(point.x, point.y);
    if (element) {
        element.select();
    }
});

Node.js Server Usage

const { FabberSVG, Document } = require('fabber-svg-api');

// Generate SVG on server
function generateDiagram(data) {
    const doc = new Document({ width: 800, height: 600 });

    data.forEach((item, index) => {
        const rect = new Rectangle({
            x: index * 100 + 50,
            y: 200,
            width: 80,
            height: item.value * 2,
            fill: item.color
        });
        doc.addElement(rect);
    });

    return doc.exportSVG();
}

This API reference provides the foundation for building powerful applications with Fabber SVG 2025. For more examples and detailed documentation, visit our GitHub repository.