v8.48.3

Replace sticker background image

We can use the willRenderShapeControls property to add a "select image" button above a sticker shape.

We'll use a custom browse() function to select a new image from the file sytem.

<!DOCTYPE html>

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

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

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

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

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

    const browse = (options) => {
        return new Promise((resolve) => {
            const element = document.createElement('input');
            element.type = 'file';
            element.accept = options.accept;
            element.onchange = () => {
                const [file] = element.files;
                if (!file) return resolve();
                resolve(file);
            };
            element.click();
        });
    };

    const editor = appendDefaultEditor('#editor', {
        src: 'image.jpeg',
        imageAnnotation: [
            {
                x: 128,
                y: 128,
                width: 512,
                height: 384,
                backgroundSize: 'contain',
                backgroundImage: './my-sticker.jpeg',
            },
        ],
        willRenderShapeControls: (controls, selectedShapeId) => {
            controls[0][3].push(
                // Add a "Select image" button
                createNode('Button', 'my-button', {
                    label: 'Select image',
                    onclick: async () => {
                        // Find the currently selected shape
                        const shape = editor.imageAnnotation.find(
                            (shape) => shape.id === selectedShapeId
                        );

                        // browse for an image
                        const file = await browse({
                            accept: 'image/*',
                        });

                        // no file selected
                        if (!file) return;

                        // update background image
                        shape.backgroundImage = URL.createObjectURL(file);

                        // redraw annotations
                        editor.imageAnnotation = editor.imageAnnotation;
                    },
                })
            );
            return controls;
        },
    });

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