The Canvas component is the core of the editor. You can control it using a ref of type CanvasInstance. The canvasRef.current.handler provides an API to manipulate the canvas, such as adding objects, exporting/importing JSON, and managing undo/redo history.
Key Props:
ref: A CanvasInstance ref to access the handler.style: Must provide a visible height (especially for responsive sizing).canvasOption: Configuration for the canvas (e.g., backgroundColor).workareaOption: Configuration for the drawing area (e.g., width, height, backgroundColor).canvasActions: Enables features like clipboard and transaction (undo/redo).onSelect: Callback triggered when an object is selected.
import { useRef } from 'react';
import { Canvas, type CanvasInstance } from 'react-design-editor';
import 'react-design-editor/react-design-editor.css';
export default function DesignCanvas() {
const canvasRef = useRef<CanvasInstance | null>(null);
const addRectangle = () => {
canvasRef.current?.handler.add({
type: 'rect',
name: 'Rectangle',
width: 160,
height: 90,
fill: '#5ee0bd',
rx: 8,
ry: 8,
});
};
const saveCanvas = () => {
const objects = canvasRef.current?.handler.exportJSON() ?? [];
localStorage.setItem('design', JSON.stringify(objects));
};
const loadCanvas = async () => {
const saved = localStorage.getItem('design');
if (saved) {
await canvasRef.current?.handler.importJSON(JSON.parse(saved));
}
};
return (
<div>
<button type="button" onClick={addRectangle}>Add rectangle</button>
<button type="button" onClick={saveCanvas}>Save</button>
<button type="button" onClick={loadCanvas}>Load</button>
<Canvas
ref={canvasRef}
style={{ width: '100%', height: 600 }}
canvasOption={{ backgroundColor: '#f4f7f9' }}
workareaOption={
{
width: 800,
height: 500,
backgroundColor: '#ffffff',
},
}
canvasActions={
{
clipboard: true,
transaction: true,
},
}
onSelect={object => {
console.log('Selected object:', object);
}},
/>
</div>
);
}