Apply a circular mask to the image

We can use the postProcessImageData property on the createDefaultImageWriter function to change the imageData before the output file is created.

To show a circular overlay in the editor itself see the circular crop overlay example.

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

// Open the default image editor in a modal
const editor = openDefaultEditor({
    src: './my-image.jpeg',

    // We'll request a square crop
    imageCropAspectRatio: 1,

    // Let's apply a circle mask to the output image
    imageWriter: createDefaultImageWriter({
        // Scale down the output image
        targetSize: {
            width: 256,
            height: 256,
        },
        // Convert to PNG so masked area is transparent
        mimeType: 'image/png',

        // Run custom processing on the image data
        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));
            }),
    }),
});

// Show resulting image preview
editor.on('process', ({ dest }) => {
    const preview = new Image();
    preview.src = URL.createObjectURL(dest);
    document.body.appendChild(preview);
});