Skip to content

Getting Started with FxCanvas

FxCanvas is a high-performance canvas encoding library that allows you to programmatically create images by building a sequence of drawing operations. Unlike traditional canvas APIs, FxCanvas encodes your drawing commands into a compact binary format that can be rendered server-side via API calls.

Installation

bash
npm install fxcanvas

Basic Usage

javascript
import { CanvasEncoder, Color } from 'fxcanvas';

// Create a new canvas encoder with dimensions
const canvas = new CanvasEncoder(400, 200);

// Set up styles
canvas.setFillStyle(new Color(255, 0, 0)); // Red
canvas.setStrokeStyle(new Color(0, 0, 255)); // Blue
canvas.setLineWidth(2);

// Draw shapes
canvas.fillRect(50, 50, 100, 100);
canvas.strokeRect(200, 50, 100, 100);

// Generate the render request
const request = canvas.getRequest({
  token: 'your-api-token',
  format: CanvasImageFormat.Png,
  quality: 90
});

// Send to rendering service
fetch(request);

Core Concepts

CanvasEncoder

The main class that records all drawing operations. It maintains state for styles, transformations, and builds the binary encoding.

Colors, Gradients, and Patterns

FxCanvas uses dedicated classes for styling:

  • Color for solid colors (supports named colors, RGB, HSV, hex)
  • LinearGradient/RadialGradient for smooth color transitions
  • Pattern for tiled textures

Fonts and Text

Text rendering uses FontFace objects for custom fonts and Font descriptors for styling.

Images

Images are loaded via the Image class and drawn with drawImage().

Extensions

Specialized contexts for QR codes (QRContext) and AI-generated images (Txt2ImgContext).

Rendering Workflow

  1. Create Encoder: Initialize CanvasEncoder with dimensions
  2. Build Operations: Call drawing methods to encode operations
  3. Generate Request: Use getRequest() to create an API request
  4. Render: Send the request to get the final image

Next Steps