Using placeholders 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.
import { openDefaultEditor } from './pintura.js';
// Open the default image editor in a modal
const editor = openDefaultEditor({
src: './my-image.jpeg',
// Add an annotation to the image
imageAnnotation: [
{
x: 128,
y: 128,
fontSize: 96,
fontWeight: 'bold',
color: [1, 1, 1],
// We'll replace {name} when processing the image
text: 'Hello {name}',
},
],
// Let's apply a circle mask to the output image
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;
},
},
});
// Log errors to console
editor.on('error', console.error);
// Show resulting image preview
editor.on('process', ({ dest }) => {
const preview = new Image();
preview.src = URL.createObjectURL(dest);
document.body.appendChild(preview);
});