Exports

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

These module exports can be imported like shown below.

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

When using the IIFE version of Doka we can access the exported properties like this.

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

Editor

Property Description
setPlugins(...args) Registers the supplied plugins with Doka Image Editor. Needs to be called before creating the editor.
appendEditor(selector, obj) Appends editor to the DOM and returns a single editor instance.
appendEditors(selector, obj) Appends multiple editors to the DOM and returns an array of editor instances.
openEditor(obj) Opens the editor in a modal.
overlayEditor(selector, obj) Overlays the editor UI on top of an image.
defineCustomElements() Register the <doka-image-editor> Custom Element.
createDefaultImageOrienter() Creates a helper object to correctly orient images.
createDefaultImageReader(obj) Creates the default image reader. This is the array of processes the editor uses to read image data.
createDefaultImageWriter(obj) Creates the default image writer. This is the array of processes the editor uses to write image data.
processImage(file, obj) processes the file with supplied properties.
dispatchEditorEvents(editor, target) Dispatches the Doka 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(obj) Converts a Doka Image Editor legacy data object to an imageState object.
isSupported() Returns true if the current browser supports Doka Image Editor.

openEditor

Opens the editor in a modal.

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

openEditor({
    /* options here */
});

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 a default image reader array. This is an array of processes the editor runs to read image data.

Property 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 './doka.js';

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

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

Example of the filtered output data 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',
};

Turning HEIC/HEIF images into a readable format using Heic2any in the preprocessImageFile hook.

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

const imageReader = createDefaultImageReader({
    preprocessImageFile: async (file, options, onprogress) => {
        // If is HEIC, we preprocess to a readable image format
        if (/heic/.test(file.type)) {
            // let's turn HEIC into JPEG so the browser can read it
            const blob = await heic2any({
                blob: file,
                toType: 'image/jpeg',
                quality: 0.94,
            });

            // Doka Image Editor expects a File
            return blobToFile(blob, file.name);
        }

        // no need to preproces
        return file;
    },
});

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.

Property 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.
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.
targetSize
undefined
The output size of the image
store
undefined
URL to POST FormData to, or async function for custom file upload or storage solution.
outputProps
['src', 'dest', 'imageState', 'store']
Which properties to retain on the output data object.
preprocessImageState
async (imageState) => (imageState)
Allows preprocessing the image state, 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 './doka.js';

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

    // Fix image orienation
    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. The following snippet converts all files to JPEGs and slightly compresses the result.

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

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

renameFile

Allows dynamic renaming of the output file.

import { createDefaultImageWriter } from './doka.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.

Property Default Value Description
width
undefined
The target width of the output image.
height
undefined
The target heihgt 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 './doka.js';

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

store

Store images using a custom function for the store prop.

import { createDefaultImageWriter } from './doka.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 './doka.js';

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

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

            return annotation;
        });

        // 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 './doka.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 the editor interface.

const { processImage, createDefaultImageReader, createDefaultImageWriter } = './doka.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 './doka.js';

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

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

Locale

Property Description
locale_en_gb The English language configuration object for the Editor core.
component_shape_editor_locale_en_gb The English language configuration object for the shape editor. Required when manipulating shapes in Annotate or Decorate views.

Plugins

Annotate

Property Description
plugin_annotate The annotate util view.
plugin_annotate_defaults A default annotate util configuration object exposing a set of drawing tools.
plugin_annotate_locale_en_gb The annotate util locales.

Crop

Property Description
plugin_crop The crop util view.
plugin_crop_defaults A default crop util configuration object exposing a default selection of crop presets.
plugin_crop_locale_en_gb The crop util locales.

Decorate

Property Description
plugin_decorate The decorate util view.
plugin_decorate_defaults A default decorate util configuration object exposing a set of drawing tools.
plugin_decorate_locale_en_gb The decorate util locales.

Filter

Property Description
plugin_filter The filter util view.
plugin_filter_defaults A default filter util configuration object exposing a selection of filters.
plugin_filter_locale_en_gb The filter util locales.

Finetune

Property Description
plugin_finetune The finetune util view.
plugin_finetune_defaults A default finetune util configuration object exposing a set of color adjustment controls.
plugin_finetune_locale_en_gb The finetune util locales.

Resize

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

Sticker

Property Description
plugin_sticker The sticker util view.
plugin_sticker_defaults A default sticker util configuration object.
plugin_sticker_locale_en_gb The sticker util locales.