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.

by Vijay Gujar

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/1.2.1/lodash.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.8/fabric.min.js"></script>
<script src="http://promincproductions.com/gaTrackingJSFiddle.js"></script>
<canvas id="c" width="400" height="400"></canvas>

CSS

#c {
    border:0px solid #ccc;
}

JavaScript

var img01URL = 'https://www.google.com/images/srpr/logo4w.png';
var img02URL = 'http://fabricjs.com/lib/pug.jpg';

var canvas = new fabric.Canvas('c');
canvas.controlsAboveOverlay = true;
canvas.setZoom(2.5);
// 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',
    angle: 0,
    left: 195,
    top: 0,
    width: 200,
    height: 200,
    fill: 'transparent', /* 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.
clipRect1.set({
    //clipFor: 'pug',
    angle: 0
});
//canvas.add(clipRect1);




// Since the `angle` property of the Image object is stored 
// in degrees, we'll use this to convert it to radians.
function degToRad(degrees) {
    return degrees * (Math.PI / 180);
}

var _objects = [];
var pugImg = new Image();
//pugImg.onload = function (img) {    
    var pug = new fabric.Text("Hi ", {
        angle: 0,
        width: 500,
        height: 500,
        left: 180,
        top: 35,
        scaleX: 1,
        scaleY: 1,
        //clipName: 'pug',
        clipTo: function(ctx) { 
            ctx.save();
              ctx.setTransform(1, 0, 0, 1, 0, 0);
              
            clipRect1.render(ctx);
            ctx.strokeStyle = "red";
            ctx.stroke();
              ctx.restore();
        }
    });
    //canvas.add(pug);
    _objects.push(pug);
    var pug1 = new fabric.Text("Hello", {
        angle: 0,
        width: 500,
        height: 500,
        left: 245,
        top: 135,
        scaleX: 1,
        scaleY: 1,
        //clipName: 'pug',
        /* clipTo: function(ctx) { 
            ctx.save();
              ctx.setTransform(1, 0, 0, 1, 0, 0);
              
           ...