This tutorial shows how to implement undo/redo functionality in marker.js 3.
marker.js provides built-in undo/redo functionality through the MarkerArea component. The key concepts we'll use are:
isUndoPossible
and isRedoPossible
properties to check stateundo()
and redo()
methods to perform operationsareastatechange
event to track changesWe'll build a complete implementation that includes:
First, create a basic marker.js setup:
import { MarkerArea } from '@markerjs/markerjs3';
const targetImage = document.getElementById('imageToMark') as HTMLImageElement;
const markerArea = new MarkerArea();
markerArea.targetImage = targetImage;
document.body.appendChild(markerArea);
Add buttons to your HTML:
<button id="undoButton" disabled>Undo</button>
<button id="redoButton" disabled>Redo</button>
Connect the buttons to MarkerArea's undo/redo functionality:
const undoButton = document.getElementById('undoButton') as HTMLButtonElement;
const redoButton = document.getElementById('redoButton') as HTMLButtonElement;
// Undo handler
undoButton.addEventListener('click', () => {
if (markerArea.isUndoPossible) {
markerArea.undo();
}
});
// Redo handler
redoButton.addEventListener('click', () => {
if (markerArea.isRedoPossible) {
markerArea.redo();
}
});
Update button states based on undo/redo availability:
function updateUndoRedoButtons() {
undoButton.disabled = !markerArea.isUndoPossible;
redoButton.disabled = !markerArea.isRedoPossible;
}
// Listen for state changes
markerArea.addEventListener('areastatechange', updateUndoRedoButtons);
Here's a full working implementation:
import { MarkerArea } from '@markerjs/markerjs3';
// Setup marker.js
const targetImage = document.getElementById('imageToMark') as HTMLImageElement;
const markerArea = new MarkerArea();
markerArea.targetImage = targetImage;
document.body.appendChild(markerArea);
// Get UI elements
const undoButton = document.getElementById('undoButton') as HTMLButtonElement;
const redoButton = document.getElementById('redoButton') as HTMLButtonElement;
// Implement undo/redo
undoButton.addEventListener('click', () => {
if (markerArea.isUndoPossible) {
markerArea.undo();
}
});
redoButton.addEventListener('click', () => {
if (markerArea.isRedoPossible) {
markerArea.redo();
}
});
// Update button states
function updateUndoRedoButtons() {
undoButton.disabled = !markerArea.isUndoPossible;
redoButton.disabled = !markerArea.isRedoPossible;
}
// Listen for state changes
markerArea.addEventListener('areastatechange', updateUndoRedoButtons);