Polotno Docs
API Reference

Utility Functions

Helper functions for SVG manipulation, image processing, geometry calculations, and more

Polotno provides utility functions organized by module to help with common tasks like SVG manipulation, image processing, geometric calculations, and text measurement. These utilities are designed to work seamlessly with Polotno's data model.

polotno/utils/svg

Utilities for working with SVG strings, converting them to data URLs, and extracting color information.

svgToURL(svgString)

Converts an SVG string to a data URL that can be used as an image source.

import { svgToURL } from 'polotno/utils/svg';

const svgString = '<svg>...</svg>';
const dataURL = svgToURL(svgString);
// Returns: "data:image/svg+xml;utf8,<svg>...</svg>"

Use this when you need to display an SVG string in an <img> tag or use it as an element source.

urlToString(url)

Converts a URL (including data URLs) to a string. Useful for extracting SVG content from element sources.

import { urlToString } from 'polotno/utils/svg';

const svgString = await urlToString(element.src);
console.log(svgString); // "<svg>...</svg>"

Returns a Promise that resolves to the SVG string content. Works with both regular URLs and data URLs.

getColors(svgString)

Extracts all colors found in an SVG string. Returns an array of color values.

import { getColors, urlToString } from 'polotno/utils/svg';

const svgString = await urlToString(element.src);
const colors = getColors(svgString);
// Returns: ['#ff0000', '#00ff00', 'rgb(0,0,255)']

Use this to detect colors in SVG files for building color pickers or validation tools.

useSvgColors(src)

React hook that extracts colors from an SVG source. Returns an array of detected colors.

import { useSvgColors } from 'polotno/utils/svg';

const Toolbar = ({ element }) => {
  const colors = useSvgColors(element.src);
  // colors is an array of color strings
  
  return (
    <div>
      {colors.map((color, i) => (
        <div key={i} style={{ backgroundColor: color }} />
      ))}
    </div>
  );
};

The hook automatically handles URL resolution and SVG parsing. Use this in React components when you need reactive color detection.

polotno/utils/image

Utilities for working with image dimensions and calculating crop values.

getImageSize(src)

Asynchronously detects the dimensions of an image from a URL or data URL.

import { getImageSize } from 'polotno/utils/image';

const { width, height } = await getImageSize('https://example.com/image.jpg');
console.log(`Image is ${width}x${height} pixels`);

Returns a Promise resolving to { width: number, height: number }. Use this to get image dimensions before setting element properties.

getCrop(placeholder, imageSize)

Calculates crop values to fit an image into a placeholder element using CSS "cover" behavior. The result fills the placeholder and may crop edges if aspect ratios differ.

import { getImageSize, getCrop } from 'polotno/utils/image';

// After getting uploaded file as dataURL
const { width, height } = await getImageSize(dataURL);
const crop = getCrop(placeholder, { width, height });

placeholder.set({
  src: dataURL,
  ...crop,
  // crop contains: cropX, cropY, cropWidth, cropHeight (normalized 0-1)
});

Crop values are normalized (0-1) and can be applied directly to image elements. For "contain" behavior, resize the element instead of using crop.

polotno/utils/math

Geometric calculation utilities for bounding boxes, center points, and transformations.

getTotalClientRect(elements)

Calculates the axis-aligned bounding box of one or more elements, accounting for rotation.

import { getTotalClientRect } from 'polotno/utils/math';

const shapes = store.selectedElements;
const bbox = getTotalClientRect(shapes);
// Returns: { x: number, y: number, width: number, height: number }

Use this instead of simple x + width/2 calculations when elements may be rotated. The bounding box accounts for rotation, giving accurate visual bounds.

getClientRect(element)

Gets the bounding box of a single element, accounting for its rotation and transformations.

import { getClientRect } from 'polotno/utils/math';

const box = getClientRect(element);
// Returns: { x: number, y: number, width: number, height: number }

// Use for full-width backgrounds
backgroundEl.set({
  x: 0,
  y: box.y,
  width: element.page.computedWidth,
  height: box.height,
});

Returns the visual bounding box after applying rotation. Use this when you need precise element bounds for layout calculations.

getCenter(rect)

Calculates the center point of a rectangle.

import { getTotalClientRect, getCenter } from 'polotno/utils/math';

const bbox = getTotalClientRect(shapes);
const center = getCenter(bbox);
// Returns: { x: number, y: number }

Use this to find rotation centers for groups or multiple selections. Works with any object containing x, y, width, and height properties.

rotateAroundPoint(shape, angleDelta, center)

Rotates a shape around a specified center point by a given angle delta.

import { getTotalClientRect, getCenter, rotateAroundPoint } from 'polotno/utils/math';

const bbox = getTotalClientRect(shapes);
const center = getCenter(bbox);
const delta = 45 - (element.rotation || 0);

const newShape = rotateAroundPoint(
  {
    x: element.x,
    y: element.y,
    width: element.width,
    height: element.height,
    rotation: element.rotation || 0,
  },
  delta,
  center
);

element.set(newShape);

Returns a new shape object with updated x, y, and rotation values. Use this for programmatic rotation of elements around arbitrary points, such as the center of a selection.

polotno/utils/to-svg

Convert Polotno JSON designs to SVG strings for lightweight preview generation.

jsonToSVG(options)

Converts a Polotno JSON design to an SVG string. Useful for generating previews without mounting the full editor.

import { jsonToSVG } from 'polotno/utils/to-svg';
import { svgToURL } from 'polotno/utils/svg';

// templateJSON is your saved Polotno design
async function getThumbnailURL(templateJSON) {
  const svgString = await jsonToSVG({ json: templateJSON });
  return svgToURL(svgString); // returns data:image/svg+xml;utf8,…
}

Returns a Promise resolving to an SVG string. SVG rendering is in beta and may produce slightly different results compared to canvas rendering, but works well for preview thumbnails.

polotno/utils/to-canvas

Render individual elements to canvas elements for custom export or processing.

unstable_elementToCanvas(elementId)

Renders a single element to an HTML canvas element. Returns a Promise resolving to a canvas.

import { unstable_elementToCanvas } from 'polotno/utils/to-canvas';

const canvas = await unstable_elementToCanvas(store.selectedElements[0].id);
const dataURL = canvas.toDataURL();

Note: This function is experimental and marked as unstable_. It may change in future versions. Use with caution in production code.

The canvas can be used for further processing, conversion to images, or custom export workflows.

polotno/utils/measure-text

Measure text dimensions to check overflow or calculate dynamic layouts.

measureText(options)

Calculates how much space text will occupy given specific styling properties. Useful for checking if text will overflow a container or for dynamic layout calculations.

import { measureText } from 'polotno/utils/measure-text';

// Option 1: Pass a Polotno text element
const textElement = store.selectedElements[0];
const result = await measureText(textElement);

// Option 2: Pass text properties directly
const result = await measureText({
  text: 'Hello World',
  width: 200,
  fontSize: 16,
  fontFamily: 'Arial',
  richTextEnabled: true, // optional, defaults to global setting
});

console.log(`Text height: ${result.height}px`);

Returns a Promise resolving to { height: number }. The function automatically uses HTML rendering if richTextEnabled is true (or uses the global setting if not specified), otherwise falls back to canvas-based measurement.

Note: This function is experimental and may change in future versions.

polotno/utils/l10n

Localization utilities for translating UI strings.

t(key)

Translates a localization key to the current language string.

import { t } from 'polotno/utils/l10n';

const App = () => {
  return <div>{t('sidePanel.yourLabel')}</div>;
};

Use this in custom components to access Polotno's translation system. See Editor Configuration for details on setting up translations.

On this page