JSFiddle - React, Tailwind, and code Playground
by Vijay Gujar
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.0.0-beta.5/fabric.js"></script>
<button id='btnClip' onclick="clip()" >
Clip
</button>
<canvas id="canvas" width="500" height="500"></canvas>
JavaScript
var canvas = new fabric.Canvas('canvas');
var strokeWidth = 8;
var r1 = new fabric.Rect({
left: 0,
top: 0,
width: 70,
height: 50,
strokeWidth: strokeWidth,
stroke: '#ff00ff',
fill: 'transparent'
})
var t1 = new fabric.Textbox('Hello', {
width: 100,
height: 100,
top: 0,
left: 0,
fontSize: 52,
textAlign: 'left'
});
var g = new fabric.Group([r1,t1],{
left: 0,
top: 0
})
var mainGroup = new fabric.Group([g],{
left: 50,
top: 50
})
var mainGroupParent = new fabric.Group([mainGroup],{
left: 0,
top: 0
})
var t2 = new fabric.Textbox('Hello', {
width: 100,
height: 100,
top: 50,
left: 200,
fontSize: 52,
textAlign: 'left'
});
var txtLabel = new fabric.Textbox('Group', {
width: 100,
height: 100,
top: 20,
left: 50,
fontSize: 16,
textAlign: 'left'
});
canvas.add(txtLabel);
canvas.add(mainGroupParent);
mainGroup.left = 10;
mainGroup.top = 25;
var r2 = new fabric.Rect({
left: 200,
top: 50,
width: 70,
height: 50,
strokeWidth: strokeWidth,
stroke: '#ff00ff',
fill: 'transparent'
})
var txtLabel1 = new fabric.Textbox('Single', {
width: 100,
height: 100,
top: 20,
left: 200,
fontSize: 16,
textAlign: 'left'
});
canvas.add(txtLabel1);
canvas.add(r2);
canvas.add(t2);
canvas.renderAll();
function clip() {
//console.log(mainGroup.left)
t1.clipPath = new fabric.Rect({
left: r1.width + strokeWidth / 2,
top: r1.height + strokeWidth,
width: r1.width-strokeWidth,
height: r1.height-strokeWidth,
absolutePositioned: true,
dirty: true
})
t1.dirty = true;
g.dirty = true;
mainGroup.dirty = true;
mainGroupParent.dirty = true;
//console.log(mainGroup, t1.clipPath)
t2.clipPath = new fabric.Rect({
left: r2.left+8,
top: r2.top+8,
width: r2.width-8,
height: r2.height-8,
absolutePositioned: true,
dirty: true
})
t2.dirty = true;
canvas.renderAll();
}
var group = new fabric.Group([
...