v8.90.3

Using template placeholder values in text shapes

We can use the preprocessImageState hook exposed by the createDefaultImageWriter function to automatically replace placeholder values with real values when creating the output image.

<!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',
        imageAnnotation: [
            {
                x: 128,
                y: 128,
                fontSize: 96,
                fontWeight: 'bold',
                color: [1, 1, 1],

                // We'll replace {name} when processing the image
                text: 'Hello {name}',
            },
        ],
        imageWriter: {
            targetSize: {
                width: 512,
                height: 512,
                fit: 'contain',
            },
            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;
            },
        },
    });

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