FabricJS - Clip object to bounding box
How to use a rect as a bounding box for an image or text to allow for a clipping region or bounding box.
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/1.2.1/lodash.min.js"></script>
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c" width="400" height="400"></canvas>
<button onclick="flipObjs()">
Flip Logo Y, Flip Pug X
</button>
CSS
#c {
border:0px solid #ccc;
}
JavaScript
flipObjs = function(){
fabPug.flipX= (!fabPug.flipX);
fabLogo.flipY= (!fabLogo.flipY);
canvas.renderAll();
}
var img01URL = 'https://www.google.com/images/srpr/logo4w.png';
var img02URL = 'http://fabricjs.com/lib/pug.jpg';
var fabPug, fabLogo;
var canvas = new fabric.Canvas('c');
// Note the use of the `originX` and `originY` properties, which we set
// to 'left' and 'top', respectively. This makes the math in the `clipTo`
// functions a little bit more straight-forward.
var clipRect1 = new fabric.Rect({
originX: 'left',
originY: 'top',
left: 180,
top: 10,
width: 200,
height: 200,
fill: '#DDD', /* use transparent for no fill */
strokeWidth: 0,
selectable: false,
// We give these `Rect` objects a name property so the `clipTo` functions can
// find the one by which they want to be clipped.
clipFor: 'pug'
});
canvas.add(clipRect1);
var clipRect2 = new fabric.Rect({
originX: 'left',
originY: 'top',
left: 10,
top: 10,
width: 150,
height: 150,
fill: '#DDD', /* use transparent for no fill */
strokeWidth: 0,
selectable: false,
// We give these `Rect` objects a name property so the `clipTo` functions can
// find the one by which they want to be clipped.
clipFor: 'logo'
});
canvas.add(clipRect2);
function findByClipName(name) {
return _(canvas.getObjects()).where({
clipFor: name
}).first()
}
var clipByName = function (ctx) {
if (this.active) {
return;
}
var clipRect = findByClipName(this.clipName);
ctx.save();
var m = this.calcTransformMatrix();
var iM = fabric.util.invertTransform(m);
ctx.transform.apply(ctx, iM);
ctx.rect(
clipRect.left,
clipRect.top,
clipRect.width,
clipRect.height
);
ctx.closePath();
ctx.restore();
}
var pugImg = new Image();
pugImg.onload = function (img) {
fabPug = new fabric.Image(pugImg, {
angle: 45,
width: 500,
...