Fabric.js provides two core methods for removing canvas objects, alongside a property to configure animation speed and callback options for fade-out transitions.
Key APIs
Static Removal: canvas.remove()
This method deletes one or more objects instantly. It accepts object references as arguments and refreshes the canvas automatical if canvas.renderOnAddRemove is true (the default behavior).
// Example: Remove a static object
const greenDot = new fabric.Circle({
top: 80,
left: 80,
radius: 25,
fill: '#4CAF50'
});
canvas.add(greenDot);
canvas.remove(greenDot);
If canvas.renderOnAddRemove is explicitly set to false, the object is deleted from the canvas data structure but remains visually present until canvas.renderAll() is manually called.
Animated Removal: canvas.fxRemove()
This method removes an object with a smooth fade-out effect. It takes two arguments:
- The target object to remove
- An optional callback object with
onChange(fired on every animation frame) andonComplete(fired when the removal and animation finish)
Animation Duration: canvas.FX_DURATION
Controls the langth of the fade-out animation. The default value is 500 milliseconds.
// Increase animation duration to 2 seconds
canvas.FX_DURATION = 2000;
Complete Example
<div class="control-panel">
<button onclick="removeStaticObject()">Remove Static Circle</button>
<button onclick="removeAnimatedObject()">Remove Fade-Out Square</button>
</div>
<canvas id="fabricCanvas" width="600" height="400"></canvas>
<script src="https://cdn.bootcdn.net/ajax/libs/fabric.js/460/fabric.min.js"></script>
<script>
let canvas;
let greenCircle;
let orangeSquare;
// Initialize canvas when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
canvas = new fabric.Canvas('fabricCanvas', {
width: 500,
height: 300,
backgroundColor: '#f0f0f0'
});
// Create static circle
greenCircle = new fabric.Circle({
name: 'staticCircle',
top: 100,
left: 120,
radius: 35,
fill: '#8BC34A'
});
// Create animated square
orangeSquare = new fabric.Rect({
name: 'animatedSquare',
top: 100,
left: 300,
width: 70,
height: 70,
fill: '#FF9800'
});
canvas.add(greenCircle, orangeSquare);
});
// Remove circle instantly
function removeStaticObject() {
if (greenCircle) {
canvas.remove(greenCircle);
greenCircle = null;
}
}
// Remove square with fade-out animation
function removeAnimatedObject() {
if (orangeSquare) {
canvas.FX_DURATION = 1800;
canvas.fxRemove(orangeSquare, {
onChange() {
console.log('Fade-out animation in progress');
},
onComplete() {
console.log('Square removed successfully');
orangeSquare = null;
}
});
}
}
</script>