v8.78.1

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.

<!DOCTYPE html>

<head>
    <link rel="stylesheet" href="./pintura.css" />
</head>

<img src="" alt="" />

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

<div id="editor"></div>

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

    const editor = appendDefaultEditor('#editor', {
        src: 'image.jpeg',
        imageCropAspectRatio: 1,
        imageWriter: {
            // 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)
                    );
                }),
        },
    });

    editor.on('process', (imageState) => {
        document.querySelector('img').src = URL.createObjectURL(
            imageState.dest
        );
    });
</script>