Editor exported methods and properties

An overview of the functions, properties, defaults, plugins, and locales that the Pintura Image Editor module exports.

These module exports can be imported like shown below.

<script type="module">
    import { setPlugins, appendEditor } from './pintura.js';
</script>

When using the IIFE version of Pintura Image Editor we can access the exported properties like this.

<script src="pintura-iife.js"></script>
<script>
    pintura.setPlugins();
    pintura.appendEditor();
</script>

Editor exports

Factories

To create an editor instance use one of the following factory methods.

Export Description
appendEditor(selector, options) Appends editor to the DOM and returns a single editor instance.
appendEditors(selector, options) Appends multiple editors to the DOM and returns an array of editor instances.
openEditor(options) Opens the editor in a modal.
overlayEditor(selector, options) Overlays the editor UI on top of an image.
defineCustomElements(options) Register the <pintura-editor> Custom Element.

Default factories

The default editor factory methods below create a default editor, these factories are different from the normal factories in the following ways.

  • Automatically loads all plugins;
  • Sets the default locale to English.
  • Sets all default plugin options.
  • Hides the sticker plugin if no stickers are defined.
  • Sets the stickerStickToImage property to true.
  • Accepts a configuration object for both the imageReader and imageWriter property. The factory will automatically pass the object to the internal createDefaultImageReader and createDefaultImageWriter calls.

If we need more fine grained control over which plugins are loaded, which locale is used, and which properties are set we need to use the non-default factory methods shown in the table above.

For documentation on the default factory methods please consult the respective non-default versions (openEditor for openDefaultEditor).

Export Description
getEditorDefaults(options) Sets default plugins, sets default locale, creates a default options object, merges in the passed options object and returns the resulting object. This method is used by all default shortcut methods in this table.
appendDefaultEditor(selector, options) Sets default plugins, sets default locale, sets all default options, appends editor to the DOM and returns a single editor instance.
appendDefaultEditors(selector, options) Sets default plugins, sets default locale, sets all default options, appends multiple editors to the DOM and returns an array of editor instances.
openDefaultEditor(options) Sets default plugins, sets default locale, sets all default options, and opens the editor in a modal.
overlayDefaultEditor(selector, options) Sets default plugins, sets default locale, sets all default options, overlays the editor UI on top of an image.
defineDefaultCustomElements(options) Sets default plugins, sets default locale, sets all default options, registers the <pintura-editor> Custom Element.

Helper methods

Export Description
setPlugins(...args) Registers the supplied plugins with Pintura Image Editor. Needs to be called before creating the editor.
createDefaultImageOrienter() Creates a helper object to correctly orient images.
createDefaultImageReader(options) Creates the default image reader. This is the array of processes the editor uses to read image data.
createDefaultImageWriter(options) Creates the default image writer. This is the array of processes the editor uses to write image data.
processImage(file, options) processes the file with supplied properties.
processDefaultImage(file, options) Same as processImage but sets default image reader, image writer and image orienter.
dispatchEditorEvents(editor, target) Dispatches the Pintura Image Editor events as Custom Events on the target element.
colorStringToColorArray(str) Converts an RGB, RGBA, or HEX color string to a Color Array.
degToRad(deg) Converts degrees to radians.
blobToFile(blob, filename) Converts a Blob to a File.
legacyDataToImageState(editorRef, imageSize, legacyDataObj) Converts a Pintura Image Editor legacy data object to an imageState object.
isSupported() Returns true if the current browser supports Pintura Image Editor.
supportsWebGL() Returns true if the current browser supports WebGL.

setPlugins

The editor uses plugins to render each util view, the setPlugins method lets us register the available plugins before the editor loads.

The factory methods below automatically register all available plugins, so we won't need setPlugins when using those.

  • getEditorDefaults
  • appendDefaultEditor
  • appendDefaultEditors
  • openDefaultEditor
  • overlayDefaultEditor
  • defineDefaultCustomElements

If we're not using one of the methods above we'll have to register our plugins with the setPlugins method before calling one of the other factory methods (appendEditor, openEditor, overlayEditor, etc.).

In the example below we'll load the crop plugin, the finetune plugin, and the annotate plugin.

import {
    // The method used to register the plugins
    setPlugins,

    // The plugins we want to use
    plugin_crop,
    plugin_finetune,
    plugin_annotate,

    // Our factory method
    openEditor,
} from 'pintura.js';

// This registers the plugins with Pintura Image Editor
setPlugins(plugin_crop, plugin_finetune, plugin_annotate);

// Open the editor modal
openEditor({
    src: 'my-image.jpeg',
    /* options here */
});

openEditor

openEditor automatically creates a modal. It doesn't accept a selector or target element as the modal is added to the <body> element automatically.

The modal will automatically be shown when an image starts loading. Alternatively we can call the show and hide methods on the editor instance to manually show and hide the editor.

import { openEditor } from './pintura.js';

openEditor({
    src: 'my-image.jpeg',
    /* options here */
});

appendEditor

The appendEditor method can be used to create a single editor instance by either passing a selector or an element. Set second argument to an object to pass configuration values.

<style>
    .my-editor {
        width: 800px;
        height: 600px;
    }
</style>

<div class="my-editor"></div>

<script type="module">
    import { appendEditor } from './pintura.js';

    appendEditor('.my-editor', {
        src: 'my-image.jpeg',
        /* options here */
    });
</script>

appendEditors

Use appendEditors to create multiple instances by either passing a NodeList, an Array, or a query selector. We can also add an extra object to pass configuration values. The configuration values are deep cloned and supplied to each instance.

<style>
    .my-editor {
        width: 800px;
        height: 600px;
    }
</style>

<div class="my-editor"></div>

<div class="my-editor"></div>

<script type="module">
    import { appendEditors } from './pintura.js';

    const editors = appendEditors('.my-editor', {
        src: 'my-image.jpeg',
        /* options */
    });
</script>

overlayEditor

Renders the editor with crop controls on top of the image. Useful for "in-place" editing of images. It functions the same as appendEditor.

<style>
    .my-editor {
        width: 800px;
        height: 600px;
    }
</style>

<div class="my-editor"></div>

<script type="module">
    import { overlayEditor } from './pintura.js';

    overlayEditor('.my-editor', {
        src: 'my-image.jpeg',
        /* options here */
    });
</script>

When using this method, Pintura Image Editor will automatically:

  • Update the aspect ratio of the output image with the aspect ratio of the editor itself.
  • Zoom the preview image to fit the editor container
  • Disable the main menu.
  • Disable the crop preset dropdown.
  • Disable the crop info indicator.

The overlayEditor layout mode currently only supports showing the crop plugin.

defineCustomElements

The defineCustomElements method makes it as easy as possible to define the <pintura-editor> element. When the returned Promise resolves the Custom Element is ready for use.

Note that in the <style> tag we target the Custom Element with the pintura-editor tag selector instead of the CSS class selector .pintura-editor.

<style>
    pintura-editor {
        width: 800px;
        height: 600px;
    }
</style>

<pintura-editor src="my-image.jpeg"></pintura-editor>

<script type="module">
    import { defineCustomElements } from './pintura.js';

    defineCustomElements({
        // Pass configuration options here
    }).then((elements) => {
        // Change configuration on individual elements
    });
</script>

The Custom Element dispatches events. To prevent collisions with default events each event Pintura Image Editor fires is prepended with 'pintura:'. This means that the 'load' event is called 'pintura:load'.

The Custom Element editor instances exposes the same properties, have the same methods, and fire the same events as the "normal" JavaScript instance. So this works as you would expect.

<pintura-editor src="my-image.jpeg"></pintura-editor>

<script>
    // After the editor has been initialised
    const editor = document.querySelector('pintura-editor');

    // Change aspect ratio of image crop
    editor.imageCropAspectRatio = 1;
</script>

createDefaultImageOrienter

The createDefaultImageOrienter function returns a default image orientation helper object containing a read and an apply method to read EXIF orientation information and to write EXIF orientation information.

const imageOrienter = createDefaultImageOrienter();

console.log(imageOrienter);
// logs: { read: function, apply: function }

The returned object should be assigned to the imageOrienter property on your editor instance.

createDefaultImageReader

The createDefaultImageReader function returns the default image reader steps. This is an array of processes the editor runs to read image data.

It can read resources of type File, Blob, Data URL, URL, HTMLCanvasElement, and HTMLImageElement. It will also automatically correct mobile photo orientation when needed.

The default image reader can read images that are supported by the clients browser. In general these image formats are supported by all major browsers.

  • image/gif
  • image/png
  • image/jpeg
  • image/webp
  • image/bmp
  • image/svg

If needed we can use the preprocessImageFile hook to read additional image formats (for example HEIC).

Export Default value Description
orientImage
true
Auto corrects the orientation of mobile photos.
outputProps
['src', 'dest', 'size']
Which properties to retain on the output data object.
preprocessImageFile
async (file) => (file)
Allows preprocessing the image file, for example to turn a HEIC image into a browser supported image format.
import { createDefaultImageReader } from './pintura.js';

const imageReader = createDefaultImageReader({
    // Fix image orientation
    orientImage: true,

    // Disable output prop filter
    outputProps: [],
});

Example of the output object.

const output = {
    // the resulting file
    dest: {
        name: 'my-image.jpeg',
        lastModified: 1605802185485,
        size: 128000,
        type: 'image/jpeg',
    },
    // the image size
    size: {
        width: 1280,
        height: 1024,
    },
    // the original source
    src: './images/my-image.jpeg',
};

preprocessImageFile

The example below shows how to load HEIC/HEIF images using Heic2any in the preprocessImageFile hook.

import heic2any from './heic2any.js';
import { createDefaultImageReader, blobToFile } from './pintura.js';

const imageReader = createDefaultImageReader({
    preprocessImageFile: async (file, options, onprogress) => {
        // If is not of type HEIC we skip the file
        if (!/heic/.test(file.type)) return file;

        // Let's turn the HEIC image into JPEG so the browser can read it
        const blob = await heic2any({
            blob: file,
            toType: 'image/jpeg',
            quality: 0.94,
        });

        // The editor expects a File so let's convert our Blob
        return blobToFile(blob, file.name);
    },
});

createDefaultImageWriter

The createDefaultImageWriter function returns a default image writer array. This is an array of processes the editor runs to write the output image data.

By default it will output the src image file, the dest image file, and the imageState. If a store has been defined it will also return the store object.

Export Default value Description
canvasMemoryLimit
isIOS() ? 4096 * 4096 : Infinity
Memory limit to keep in account while drawing to canvas.
orientImage
true
Auto corrects the orientation of mobile photos.
copyImageHead
true
Copy the image head of the origin image to the output image. Only used when format is set to 'file'.
mimeType
undefined
Image mime type as a string, by default uses input image mime type.
quality
undefined
A Number between 0 and 1 indicating image quality if the requested type is image/jpeg or image/webp. If this argument is anything else, the default values 0.92 and 0.80 are used for image/jpeg and image/webp respectively. Other arguments are ignored.
renameFile
undefined
A synchronous function that receives the input file and expects a filename in return. Only called for 'file' format.
targetSize
undefined
The output size of the image
format
'file'
Format of dest property, can be set to 'file', 'imageData', or 'canvas'.
store
undefined
URL to POST FormData to, object to finetune FormData, or async function for custom file upload or storage solution. URL and object modes are only used when format is set to 'file', for other output formats use async function.
outputProps
['src', 'dest', 'imageState', 'store']
Which properties to retain on the output data object.
preprocessImageSource
async (imageSource) => (imageSource)
Allows preprocessing the source image data, for example to apply third party image optimisations or converting the file format before applying the imageState.
preprocessImageState
async (imageState) => (imageState)
Allows preprocessing the imageState, for example to replace shape placeholder text with actual content.
postprocessImageData
async (imageData) => (imageData)
Allows postprocessing the image data, for example to apply a circular crop mask.

An example implementation of createDefaultImageWriter.

import { createDefaultImageWriter } from './pintura.js';

const imageWriter = createDefaultImageWriter({
    // Scale all input canvas data to fit a 4096 * 4096 rectangle
    canvasMemoryLimit: 4096 * 4096,

    // Fix image orientation
    orientImage: true,

    // Don't retain image EXIF data
    copyImageHead: false,

    // Convert all input images to jpegs
    mimeType: 'image/jpeg',

    // Reduce quality to 50%
    quality: 0.5,

    // Post images to API at './upload'
    store: './upload',

    // Limit size of output to this size
    targetSize: {
        width: 640,
        height: 480,
        fit: 'contain',
        upscale: false,
    },

    // Show all output props
    outputProps: [],
});

canvasMemoryLimit

The amount of memory in pixels the browser can allocate to a canvas element. By default this is limited to 4096 * 4096 on iOS.

mimeType

The output image format. By default Pintura Image Editor can output in the image formats supported by the Canvas toBlob method. In general these image formats are supported by all major browsers.

  • image/png
  • image/jpeg
  • image/webp

The following snippet converts all files to JPEGs and applies a slight compression to the result.

import { createDefaultImageWriter } from './pintura.js';

const imageWriter = createDefaultImageWriter({
    mimeType: 'image/jpeg',
    quality: 80,
});

renameFile

Allows dynamic renaming of the output file.

import { createDefaultImageWriter } from './pintura.js';

const imageWriter = createDefaultImageWriter({
    renameFile: (file) =>
        `output_${name.substr(0, name.lastIndexOf('.'))}.jpeg`,
});

targetSize

Limit the output size of images to the defined width and height.

Export Default value Description
width
undefined
The target width of the output image.
height
undefined
The target height of the output image.
fit
'contain'
The method of resizing the input image, can be set to 'contain', 'cover', or 'force'.
upscale
false
Should the input image data be upscaled to the supplied width and height.

Make sure output images are contained within a 640 × 640 rectangle. If images are smaller they won't be upscaled.

import { createDefaultImageWriter } from './pintura.js';

const imageWriter = createDefaultImageWriter({
    targetSize: {
        width: 640,
        height: 640,
        fit: 'contain',
        upscale: false,
    },
});

store

The store property accepts a URL, a store configuration object, or a Function.

If we set a URL the editor will POST the output file and image state to that location as FormData. It will use "dest" as name for the file field, and "imageState" as name for the JSON string of the imageState object.

The XMLHttpRequest instance used to POST the data will be stored in the store property of the image writer output data object.

import { openEditor, createDefaultImageWriter } from './pintura.js';

const editor = openEditor({
    imageWriter: createDefaultImageWriter({
        store: './my-custom-upload',
    })
})

editor.on('process', { store, dest } => {
    // `store` is the XMLHttpRequest instance used for uploading the file,
    // it contains all request information
})

We can pass a configuration object to alter the defaults fields or add additional fields. It still allows us to set the url but now we can set a dataset Function. This Function receives the state and allows selecting data and naming fields.

import { createDefaultImageWriter } from './pintura.js';

const imageWriter = createDefaultImageWriter({
    store: {
        url: './my-custom-upload',
        dataset: (state) => [
            ['imageFile', state.dest, state.dest.name],
            ['imageState', state.imageState],
        ],
    },
});

If we need more control we can set a Function to the store property. This Function should return a Promise.

In the example below we run a custom upload function to store data in the imageState.

import { createDefaultImageWriter } from './pintura.js';

const imageWriter = createDefaultImageWriter({
    store: (state, options, onprogress) =>
        new Promise((resolve, reject) => {
            const { dest } = state;

            // create a formdata object to send to the server
            const formData = new FormData();
            formData.append('image', dest, dest.name);

            // create a request object
            const request = new XMLHttpRequest();
            request.open('POST', './upload');

            // show progress in interface
            request.upload.onprogress = onprogress;

            // catch errors
            request.onerror = () => reject('oh no something went wrong!');
            request.ontimeout = () => reject('oh no request timed out!');

            // handle success state
            request.onload = () => {
                if (request.status >= 200 && request.status < 300) {
                    // store request in state so it can be accessed by other processes
                    state.store = request;
                    resolve(state);
                } else {
                    reject('oh no something went wrong!');
                }
            };

            // start uploading the image
            request.send(formData);
        }),
});

preprocessImageState

This hook allows us to pre-process the imageState object before it's used to generate the output image.

In the example below we replace all name placeholders in annotation text values with the name "John Connor".

import { createDefaultImageWriter } from './pintura.js';

const imageWriter = createDefaultImageWriter({
    preprocessImageState: (imageState) => {
        // create new annotation array
        imageState.annotation = imageState.annotation.map((shape) => {
            // this is not a text shape so skip
            if (!shape.text) return shape;

            // replace placeholders in text properties
            shape.text = shape.text.replace(/\{name\}/g, 'John Connor');

            return shape;
        });

        // return updated image state
        return imageState;
    },
});

postprocessImageData

Run post image processing on the imageData the editor outputs. The example snippet below will apply a circular crop mask to the image.

import { createDefaultImageWriter } from './pintura.js';

const imageWriter = createDefaultImageWriter({
    postprocessImageData: (imageData) =>
        new Promise((resolve) => {
            // create a canvas element to handle the imageData
            const canvas = document.createElement('canvas');
            canvas.width = imageData.width;
            canvas.height = imageData.height;
            const ctx = canvas.getContext('2d');
            ctx.putImageData(imageData, 0, 0);

            // only draw image where we render our circular mask
            ctx.globalCompositeOperation = 'destination-in';

            // draw our circular mask
            ctx.fillStyle = 'black';
            ctx.beginPath();
            ctx.arc(
                imageData.width * 0.5,
                imageData.height * 0.5,
                imageData.width * 0.5,
                0,
                2 * Math.PI
            );
            ctx.fill();

            // returns the modified imageData
            resolve(ctx.getImageData(0, 0, canvas.width, canvas.height));
        }),
});

processImage

Use the processImage method to process images without loading the editor interface.

import {
    processImage,
    createDefaultImageReader,
    createDefaultImageWriter,
} from './pintura.js';

const res = await processImage('./my-image.jpeg', {
    imageReader: createDefaultImageReader(),
    imageWriter: createDefaultImageWriter(),
    imageCrop: {
        x: 64,
        y: 64,
        width: 512,
        height: 512,
    },
    imageRotation: 0.25,
});

console.log(res);
// logs: { src:…, dest:… , imageState:…, store:… }

colorStringToColorArray

Converts CSS colors to color arrays that can be parsed by the editor.

Accepts RGB, RGBA, and HEX values.

import { colorStringToColorArray } from './pintura.js';

const shape = {
    backgroundColor: colorStringToColorArray('rgba(255, 0, 0, .5)'),
};

console.log(shape.backgroundColor);
// logs: [1, 0, 0, .5]

legacyDataToImageState

Converts legacy v6 data objects to imageState objects.

Needs the image size and a reference to the editor instance to correctly calculate the imageState.

const editor = openEditor({
    src: 'my-image.jpeg',
});

editor.on('load', ({ size }) => {
    editor.imageState = legacyDataToImageState(editor, size, legacyDataObject);
});

NodeTree

The NodeTree helper methods can be used to make interaction with internal node trees easier. These methods can be used with the willRenderToolbar, the willRenderShapeControls, and the willRenderShapePresetToolbar methods.

Export Description
createNode(type, id, props?, children?) Creates a new HTML element or component definition.
findNode(id, parent) Finds a node object in a node list or another node.
appendNode(node, parent) Appends a node to either a node list or to another node.
removeNode(node, parent) Removes a node from a node list or another node.
insertNodeBefore(node, id, parent) Inserts a node before the node with id in a node list or another node.
insertNodeAfter(node, id, parent) Inserts a node before the node with id in a node list or another node.

createNode

The createNode function takes four parameters.

createNode(type, id, props, children);

The type should be either an HTML tag name (currently only 'div' is supported), a name of a Pintura component ('Button', or 'Dropdown'), or a custom Svelte component.

Because of Svelte internals currently only the 'div' tag is supported.

The id argument should be set to a unique id.

The props argument can be set to an object with properties or attributes to set to the control. If the type argument is an HTML node name, the properties will be set as attributes on the created node. The textContent property is an exception to this, it will set the inner text of the created node (innerHTML is currently not supported).

The children argument can be set to an array of nodes. This argument is only available when the type argument is set to an HTML node name.

import { createNode } from './pintura.js';

// Creating a <div> with text
const myDiv = createNode('div', 'my-div', {
    class: 'my-div-class',
    textContent: 'hi',
});

// Creating a Button component
const myNode = createNode('Button', 'my-button', {
    // The button label
    label: 'Hello world',
    // An optional button SVG icon
    icon: '<rect x="0" y="0" width="24" height="24" fill="red"/>',
    // A click event handler
    onclick: () => {
        /* do something here */
    },
});

// Creating a <div> with a Button inside it
const myDiv = createNode(
    'div',
    'my-div',
    {
        class: 'my-div-class',
        textContent: 'hi',
    },
    [createNode('Button', 'my-button', { label: 'Hello World' })]
);

Locale exports

Export Description
locale_en_gb The English language configuration object for the Editor core.
markup_editor_locale_en_gb The English language configuration object for the Markup Editor. Required when manipulating shapes in Annotate and/or Decorate plugins.

Plugins exports their own locale objects, for more information skip to Plugins.

Markup exports

The markup helper methods make it easier to create the Markup Editor tools and shape style controls that are available in the annotate and decorate plugings.

Export Description
markup_editor_defaults An object containing default tools and shape styles.
createMarkupEditorToolbar(tools) A function that creates the default Markup Editor toolbar object.
createMarkupEditorToolStyles(styles) A function that creates the default Markup Editor tool styles object.
createMarkupEditorToolStyle(type, shape) A function that creates a new tool style object.
createMarkupEditorShapeStyleControls(controls) A function that creates a new shape style control configuration object.

Helper methods to create style controls, these return a style control with the supplied options.

import {
    createMarkupEditorBackgroundColorControl,
    createMarkupEditorColorOptions,
} from './pintura.js';

const backgroundStyleControl = createMarkupEditorBackgroundColorControl(
    createMarkupEditorColorOptions({
        red: [1, 0, 0],
        green: [0, 1, 0],
        blue: [0, 0, 1],
    })
);
Export Description
createMarkupEditorBackgroundColorControl(colorOptions) Helper method to create the default background color control configuration.
createMarkupEditorStrokeColorControl(colorOptions) Helper method to create the default stroke color control configuration.
createMarkupEditorStrokeWidthControl(sizeOptions) Helper method to create the default stroke width control configuration.
createMarkupEditorLineStartStyleControl(styleOptions) Helper method to create the default line start control configuration.
createMarkupEditorLineEndStyleControl(options) Helper method to create the default line end control configuration.
createMarkupEditorFontColorControl(options) Helper method to create the default font color control configuration.
createMarkupEditorFontFamilyControl(options) Helper method to create the default font family control configuration. This control will automatically test if the defined fonts are available, if not, they will be automatically hidden.
createMarkupEditorFontStyleControl(options) Helper method to create the default font style control configuration.
createMarkupEditorFontSizeControl(options) Helper method to create the default font size control configuration.
createMarkupEditorTextAlignControl(options) Helper method to create the default text align control configuration.

Helper methods to transform readable option objects and arrays into options that can be consumed by shape controls.

import { createMarkupEditorColorOptions } from './pintura.js';

const colorOptions = createMarkupEditorColorOptions({
    red: [1, 0, 0],
    green: [0, 1, 0],
    blue: [0, 0, 1],
});
Export Description
createMarkupEditorColorOptions(options) Helper method to create the default color options array.
createMarkupEditorFontSizeOptions(options) Helper method to create the default font size options array.
createMarkupEditorFontScaleOptions(options) Helper method to create the default font scale options array.
createMarkupEditorStrokeWidthOptions(options) Helper method to create the default stroke width options array.
createMarkupEditorStrokeScaleOptions(options) Helper method to create the default stroke scale options array.
createMarkupEditorFontFamilyOptions(options) Helper method to create the default font family options array.
createMarkupEditorFontStyleOptions(options) Helper method to create the default font style options array.
createMarkupEditorLineEndStyleOptions(options) Helper method to create the default line end style options array.

Create default sets of markup options.

import { createDefaultColorOptions } from './pintura.js';

const colorOptions = createDefaultColorOptions();

console.log(colorOptions);

// logs { transparent: [1, 1, 1, 0], white: [1, 1, 1], silver: [0.8667, 0.8667, 0.8667] ... }
Export Description
createDefaultColorOptions() Returns the default color options array.
createDefaultFontSizeOptions() Returns the default font size options array.
createDefaultFontScaleOptions() Returns the default font scale options array.
createDefaultStrokeWidthOptions() Returns the default stroke width options array.
createDefaultStrokeScaleOptions() Returns the default stroke scale options array.
createDefaultLineEndStyleOptions() Returns the default line end style options array.
createDefaultFontFamilyOptions() Returns the default font family options array.
createDefaultFontStyleOptions() Returns the default font style options array.
createDefaultTextAlignOptions() Returns the default text align options array.

markup_editor_defaults

This will set the default Markup Editor settings and locale.

import {
    openEditor,
    markup_editor_defaults,
    markup_editor_locale_en_gb,
} from './pintura.js';

openEditor({
    ...markup_editor_defaults,
    locale: {
        ...markup_editor_locale_en_gb,
    },
});

Instead of using markup_editor_defaults this also sets the default tool options.

import {
    openEditor,
    createMarkupEditorToolbar,
    createMarkupEditorToolStyles,
    createMarkupEditorShapeStyleControls,
} from './pintura.js';

openEditor({
    markupEditorToolbar: createMarkupEditorToolbar(),
    markupEditorToolStyles: createMarkupEditorToolStyles(),
    markupEditorShapeStyleControls: createMarkupEditorShapeStyleControls(),
});

createMarkupEditorToolbar

This is a helper function to create the Markup Editor toolbar. If no parameters are passed the function creates the default Markup Editor toolbar array.

We can assign the return value of this function to the markupEditorToolbar property to update the toolbar.

import { openEditor, createMarkupEditorToolbar } from './pintura.js';

const defaultTools = createMarkupEditorToolbar();

openEditor({
    markupEditorToolbar: defaultTools,
});

To create a custom toolbar we can either pass an array of strings or an array of arrays.

const myToolbar = createMarkupEditorToolbar(['eraser', 'sharpie', 'rectangle']);

Each tool key ('eraser', 'sharpie', 'rectangle') links to a label and icon in the markup locale file. It also links to a shape style for that key, this style is defined in the markupEditorToolStyles property.

To find the label and optional icon the first character of the tool key is automatically uppercased and then the key is appended to shapeLabelTool to get the label, and shapeIconTool to get the icon.

'sharpie' -> 'Sharpie' -> locale.shapeLabelToolSharpie
'sharpie' -> 'Sharpie' -> locale.shapeIconToolSharpie

We can also pass an array instead of a string. In this case the first index of the array should be the tool key.

The array can be either two or three items in length.

// The label for key 'sharpie' should be available in the locale object
createMarkupEditorToolbar([['sharpie', { disabled: true }]]);

// The label 'Pen' is used
createMarkupEditorToolbar([['sharpie', 'Pen']]);

// The label 'Pen' is used and the tool is disabled
createMarkupEditorToolbar([['sharpie', 'Pen', { disabled: true }]]);

The example below will define three tools and disable the eraser tool.

const myToolbar = createMarkupEditorToolbar([
    ['eraser', { disabled: true }],
    'sharpie',
    'rectangle',
]);

In the example below we add a custom 'marker' tool. It'll use the label 'Marker' and the icon defined in the icon property. The style of the tool will be defined with key 'marker'.

const myToolbar = createMarkupEditorToolbar([
    ['eraser', { disabled: true }],
    'sharpie',
    ['marker', 'Marker', { icon: '<g></g>' }]
    'rectangle',
]);

createMarkupEditorToolStyles

Running this helper function without parameters will return the default tool styles.

We can assign the return value of this function to the markupEditorToolStyles to update the tool default styles.

import { openEditor, createMarkupEditorToolStyles } from './pintura.js';

const defaultToolStyles = createMarkupEditorToolStyles();

openEditor({
    markupEditorToolStyles: defaultToolStyles,
});

We can add custom styles by passing a configuration object to the function, use the createMarkupEditorToolStyle function to create a custom style object.

The createMarkupEditorToolStyles function will merge the passed configuration object with the default tool styles. This allows adding tool styles or altering existing tool styles.

const myToolStyles = createMarkupEditorToolStyles({
    // <tool-key>: <tool-default-style>
    marker: undefined,
});

Let's look at the createMarkupEditorToolStyle function to see how we can assign a custom style.

createMarkupEditorToolStyle

The createMarkupEditorToolStyle function expects three parameters, the type of the shape, the shape properties that should be assigned and the shape options. The return value should be set to a tool key in the markupEditorToolStyles object.

Type can be either 'path', 'rectangle', 'ellipse', 'line', or 'text'. The function will return a set of default styles.

import {
    openEditor,
    createMarkupEditorToolStyles,
    createMarkupEditorToolStyle,
} from './pintura.js';

const defaultPathStyle = createMarkupEditorToolStyle('path');

openEditor({
    markupEditorToolStyles: createMarkupEditorToolStyles({
        marker: defaultPathStyle,
    }),
});

Below we create a marker that has a fixed width as we've used the disableStyle property to prevent rendering of the strokeWidth shape style control. We also use the createDefaultColorOptions function to get a set of default colors so we can assign the strokeColor.

import {
    createDefaultColorOptions,
    createMarkupEditorToolStyle,
} from './pintura.js';

const ColorOptions = createDefaultColorOptions();

const myPathStyle = createMarkupEditorToolStyle('path', {
    strokeWidth: '5%',
    strokeColor: ColorOptions.red,
    disableStyle: ['strokeWidth'],
});

createMarkupEditorShapeStyleControls

The createMarkupEditorShapeStyleControls function creates the default set of shape style controls which can be assigned to the markupEditorShapeStyleControls property.

We can use this method to override default style options. Set a style property to false to disable it or set a property to a list of options to override the default options.

This will disable the fontFamily dropdown.

import { openEditor, createMarkupEditorShapeStyleControls } from './pintura.js';

openEditor({
    markupEditorShapeStyleControls: createMarkupEditorShapeStyleControls({
        fontFamilyOptions: false,
    }),
});

This will change the default fontFamily dropdown options.

import { openEditor, createMarkupEditorShapeStyleControls } from './pintura.js';

openEditor({
    markupEditorShapeStyleControls: createMarkupEditorShapeStyleControls({
        fontFamilyOptions: [
            ['arial', 'Arial'],
            ['open-sans', 'Open Sans'],
            ['courier', 'Courier'],
        ],
    }),
});

Markup option defaults

createDefaultColorOptions

Returns the following object of default color options.

{
    transparent: [1, 1, 1, 0],
    white: [1, 1, 1],
    silver: [0.8667, 0.8667, 0.8667],
    gray: [0.6667, 0.6667, 0.6667],
    black: [0, 0, 0],
    navy: [0, 0.1216, 0.2471],
    blue: [0, 0.4549, 0.851],
    aqua: [0.498, 0.8588, 1],
    teal: [0.2235, 0.8, 0.8],
    olive: [0.2392, 0.6, 0.4392],
    green: [0.1804, 0.8, 0.251],
    yellow: [1, 0.8627, 0],
    orange: [1, 0.5216, 0.1059],
    red: [1, 0.2549, 0.2118],
    maroon: [0.5216, 0.0784, 0.2941],
    fuchsia: [0.9412, 0.0706, 0.7451],
    purple: [0.6941, 0.051, 0.7882],
}

createDefaultFontSizeOptions

Returns the following array of fixed font sizes.

[16, 18, 20, 24, 30, 36, 48, 64, 72, 96, 144];

createDefaultFontScaleOptions

Returns the following object containing a selection of relative font sizes.

{
    extraSmall: '2%',
    small: '4%',
    mediumSmall: '8%',
    medium: '10%',
    mediumLarge: '15%',
    large: '20%',
    extraLarge: '25%',
}

createDefaultStrokeScaleOptions

Returns the following object containing a selection of relative stroke widths.

{
    extraSmall: '0.25%',
    small: '0.5%',
    mediumSmall: '1%',
    medium: '1.75%',
    mediumLarge: '2.5%',
    large: '3.5%',
    extraLarge: '5%',
}

createDefaultStrokeWidthOptions

Returns the following array of fixed stroke widths.

[1, 2, 3, 4, 6, 8, 12, 16, 20, 24, 32, 48];

createDefaultLineEndStyleOptions

Returns the following array of line end styles.

[
    'bar',
    'arrow',
    'arrowSolid',
    'circle',
    'circleSolid',
    'square',
    'squareSolid',
];

createDefaultFontFamilyOptions

Returns the following array of font families. The font family control automatically tests if a font family is available on the user device, if not, it will hide the option.

[
    [`Helvetica, Arial, Verdana, 'Droid Sans', sans-serif`, 'Sans Serif'],
    [`'Arial Black', 'Avenir-Black', 'Arial Bold'`, 'Black'],
    [`'Arial Narrow', 'Futura-CondensedMedium'`, 'Narrow'],
    [`'Trebuchet MS'`, 'Humanist'],
    [
        `Georgia, 'Avenir-Black', 'Times New Roman', 'Droid Serif', serif`,
        'Serif',
    ],
    [`Palatino`, 'Old-Style'],
    [`'Times New Roman', 'TimesNewRomanPSMT'`, 'Transitional'],
    [`Menlo, Monaco, 'Lucida Console', monospace`, 'Monospaced'],
    [`'Courier New', monospace`, 'Slab Serif'],
];

createDefaultFontStyleOptions

Returns the following array of font styles. These are applied to the fontStyle and fontWeight shape properties.

[
    ['normal', 'bold'],
    ['italic', 'normal'],
    ['italic', 'bold'],
];

createDefaultTextAlignOptions

Returns the following array.

['left', 'center', 'right'];

Plugins

Annotate plugin exports

Export Description
plugin_annotate The annotate util view.
plugin_annotate_locale_en_gb The annotate util locales.

Crop plugin exports

Export Description
plugin_crop The crop util view.
plugin_crop_locale_en_gb The crop util locales.

Decorate plugin exports

Export Description
plugin_decorate The decorate util view.
plugin_decorate_locale_en_gb The decorate util locales.

Filter plugin exports

Export Description
plugin_filter The filter util view.
plugin_filter_defaults A default filter util configuration object exposing a selection of the filters below.
plugin_filter_locale_en_gb The filter util locales.
filterPastel The Pastel filter.
filterChrome The Chrome filter.
filterFade The Fade filter.
filterWarm The Warm filter.
filterCold The Cold filter.
filterInvert The Invert filter.
filterMonoDefault The Mono default filter.
filterMonoNoir The Mono Noir filter.
filterMonoWash The Mono Wash filter.
filterMonoStark The Mono Stark filter.
filterSepiaDefault The Sepia default filter.
filterSepiaBlues The Sepia Blues filter.
filterSepiaRust The Sepia Rust filter.
filterSepiaColor The Sepia Color filter.

Finetune plugin exports

Export Description
plugin_finetune The finetune util view.
plugin_finetune_defaults A default finetune util configuration object exposing a selection of the color adjustment controls below.
plugin_finetune_locale_en_gb The finetune util locales.
effectBrightness The Brightness effect control.
effectContrast The Contrast effect control.
effectSaturation The Saturation effect control.
effectExposure The Exposure effect control.
effectGamma The Gamma effect control.
effectVignette The Vignette effect control.
effectClarity The Clarity effect control.
effectTemperature The Temperature effect control.

Resize

Export Description
plugin_resize The resize util view.
plugin_resize_locale_en_gb The resize util locales.

Sticker plugin exports

Export Description
plugin_sticker The sticker util view.
plugin_sticker_locale_en_gb The sticker util locales.