JSFiddle - React, Tailwind, and code Playground
HTML
<div class="container">
<canvas id="c" width="750" height="400" style="border:1px solid #ccc"></canvas>
<br>
<button onclick="changeClipPath()">Change Clip Path</button>
<button onclick="nestedClipPath()">Nested Clip Path</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.1/fabric.min.js" integrity="sha512-CeIsOAsgJnmevfCi2C7Zsyy6bQKi43utIjdA87Q0ZY84oDqnI0uwfM9+bKiIkI75lUeI00WG/+uJzOmuHlesMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
JavaScript
// Initialize canvas
const canvas = new fabric.Canvas('c');
// Create initial circular clip path
const circleClip = new fabric.Circle({
radius: 70,
top: -70,
left: -70,
});
// Create a group of colored rectangles
const group = new fabric.Group([
new fabric.Rect({ width: 100, height: 100, fill: 'red' }),
new fabric.Rect({ width: 100, height: 100, fill: 'yellow', left: 100 }),
new fabric.Rect({ width: 100, height: 100, fill: 'blue', top: 100 }),
new fabric.Rect({ width: 100, height: 100, fill: 'green', left: 100, top: 100 })
], {
left: 170,
top: 100,
selectable: true
});
// Apply initial circular clip path
group.clipPath = circleClip;
const frame = new fabric.Rect({ width: 300,height:300,fill:'#FF6000',absolutePositioned: true });
// Add group to canvas
canvas.add(frame)
canvas.add(group);
// Event handler for debugging
const handler = (e) => {
const target = e.target;
console.log('================== TARGET ==================');
console.log('TYPE:', target ? target.type : 'no type found');
console.log('CLIPPATH:', target ? target.clipPath.left : 'undefined');
};
// Add mouse event listener
canvas.on('mouse:down', handler);
// Function to change clip path to rectangular shape
function changeClipPath() {
const frame = new fabric.Rect({ width: 300,height:300,fill:'#FF6000',absolutePositioned: true });
const activeGroup = canvas.getActiveObject();
if (!activeGroup) {
console.log('Please select the group first');
return;
}
activeGroup.clipPath = frame;
canvas.requestRenderAll();
}
function nestedClipPath() {
const frame = new fabric.Rect({ left: 0,
top: 0, width: 300, height:300,fill:'#FF6000',absolutePositioned: true });
const activeGroup = canvas.getActiveObject();
if (!activeGroup) {
...