Skip to content

API Request Generation and Rendering

FxCanvas encodes drawing operations into a compact binary format that can be rendered server-side via API calls. The getRequest() method generates the necessary request object for submitting your encoded canvas to the rendering service.

Basic Request Generation

After building your drawing operations, generate a render request:

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

const canvas = new CanvasEncoder(800, 600);

// ... add drawing operations ...

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

// Send to rendering service
fetch('https://api.fxcanvas.com/render', {
    method: 'POST',
    body: request
})
.then(response => response.blob())
.then(blob => {
    // Handle the rendered image
    const img = new Image();
    img.src = URL.createObjectURL(blob);
    document.body.appendChild(img);
});

Request Parameters

Required Parameters

javascript
const request = canvas.getRequest({
    token: 'your-api-token',        // API authentication token
    format: 'png',                  // Output image format
    quality: 90                     // Image quality (1-100)
});

Optional Parameters

javascript
const request = canvas.getRequest({
    token: 'your-api-token',
    format: 'png',
    quality: 90,
    method: 1,                      // Rendering method (if supported)
    regions: ['eu', 'apac'],        // Storage regions for CDN
    endpoint: 'https://custom.api.com', // Custom API endpoint
    expiration: new Date(Date.now() + 3600000) // Request expiration
});

Image Formats

Choose the appropriate output format:

javascript
import { CanvasImageFormat } from 'fxcanvas';

// PNG - Best for graphics with transparency
const pngRequest = canvas.getRequest({
    token: 'token',
    format: CanvasImageFormat.Png,
    quality: 100 // PNG is lossless
});

// JPEG - Best for photographs
const jpegRequest = canvas.getRequest({
    token: 'token',
    format: CanvasImageFormat.Jpeg,
    quality: 85 // JPEG quality (1-100)
});

// WebP - Modern format with good compression
const webpRequest = canvas.getRequest({
    token: 'token',
    format: CanvasImageFormat.Webp,
    quality: 90
});

Quality Settings

Quality affects file size and visual fidelity:

javascript
// High quality for important images
const highQuality = canvas.getRequest({
    token: 'token',
    format: 'png',
    quality: 100
});

// Balanced quality for web use
const webQuality = canvas.getRequest({
    token: 'token',
    format: 'jpeg',
    quality: 85
});

// Lower quality for thumbnails
const thumbnailQuality = canvas.getRequest({
    token: 'token',
    format: 'jpeg',
    quality: 70
});

Storage Regions

Specify geographic regions for content delivery:

javascript
import { CanvasStorageRegions } from 'fxcanvas';

const request = canvas.getRequest({
    token: 'token',
    format: 'png',
    quality: 90,
    regions: [
        CanvasStorageRegions.Eu,     // Europe
        CanvasStorageRegions.Apac,   // Asia-Pacific
        CanvasStorageRegions.Enam    // North America
    ]
});

Custom Endpoints

Use custom API endpoints for self-hosted or specialized services:

javascript
const request = canvas.getRequest({
    token: 'token',
    format: 'png',
    quality: 90,
    endpoint: 'https://my-custom-api.com/render'
});

Request Expiration

Set expiration times for security:

javascript
// Expire in 1 hour
const expiration = new Date(Date.now() + (60 * 60 * 1000));

const request = canvas.getRequest({
    token: 'token',
    format: 'png',
    quality: 90,
    expiration: expiration
});

Handling Responses

Binary Image Data

javascript
fetch('/render', { method: 'POST', body: request })
.then(response => response.blob())
.then(blob => {
    // Create object URL for display
    const url = URL.createObjectURL(blob);

    // Use in img element
    const img = new Image();
    img.src = url;
    document.body.appendChild(img);

    // Or download
    const link = document.createElement('a');
    link.href = url;
    link.download = 'rendered-image.png';
    link.click();
});

JSON Responses

Some APIs may return JSON with image URLs:

javascript
fetch('/render', { method: 'POST', body: request })
.then(response => response.json())
.then(data => {
    console.log('Image URL:', data.url);
    console.log('Thumbnail URL:', data.thumbnailUrl);

    // Display the image
    const img = new Image();
    img.src = data.url;
    document.body.appendChild(img);
});

Error Handling

javascript
fetch('/render', { method: 'POST', body: request })
.then(response => {
    if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
    return response.blob();
})
.then(blob => {
    // Handle successful response
})
.catch(error => {
    console.error('Rendering failed:', error);
    // Handle error (show fallback, retry, etc.)
});

Batch Rendering

Render multiple canvases efficiently:

javascript
// Create multiple encoders
const encoders = [
    createThumbnailEncoder(),
    createPreviewEncoder(),
    createFullSizeEncoder()
];

// Generate requests
const requests = encoders.map(encoder =>
    canvas.getRequest({ token: 'token', format: 'png', quality: 90 })
);

// Send batch request (if API supports it)
fetch('/render-batch', {
    method: 'POST',
    body: JSON.stringify({ requests }),
    headers: { 'Content-Type': 'application/json' }
});

Caching and Optimization

Request Caching

Cache rendered results for repeated requests:

javascript
// Generate cache key from encoder state
const cacheKey = await canvas.getCacheKey();

const cached = await getFromCache(cacheKey);
if (cached) {
    return cached; // Use cached result
}

// Generate new request
const request = canvas.getRequest({ token: 'token', format: 'png' });
const result = await fetchAndRender(request);

// Cache the result
await saveToCache(cacheKey, result);
return result;

Progressive Loading

Request low-quality previews first:

javascript
// Fast preview
const previewRequest = canvas.getRequest({
    token: 'token',
    format: 'jpeg',
    quality: 50
});

// High quality version
const fullRequest = canvas.getRequest({
    token: 'token',
    format: 'png',
    quality: 100
});

Security Considerations

  • Keep API tokens secure and rotate regularly
  • Use HTTPS for all API communications
  • Set appropriate request expiration times
  • Validate image dimensions and parameters
  • Implement rate limiting on the client side

The request generation system makes it easy to integrate FxCanvas with rendering services, enabling scalable server-side image generation.