FabricJS - Clip object to bounding box

by Eugene Vilder

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 img02URL = 'http://fabricjs.com/lib/pug.jpg';

var canvas = new fabric.Canvas('c');


var container = new fabric.Rect({
    originX: 'center', // MUST !!!
    originY: 'center', // MUST !!!
    left: 180,
    top: 10,
    width: 200,
    height: 200,
    fill: '#DDD', /* use transparent for no fill */
    strokeWidth: 0,
    selectable: true
});

container.setPositionByOrigin({
	x: container.left,
  y: container.top
}, 'left', 'top');

container.set({
    clipFor: 'pug'
});

container.on('scaling', function(){
  console.log('Scaling', this)
});
    
canvas.add(container);



function findByClipName(name) {
    return _(canvas.getObjects()).where({
            clipFor: name
        }).first()
}

// 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 clipByName = function (ctx) {
    this.setCoords();
    var clipRect = findByClipName(this.clipName);
    var scaleXTo1 = (1 / this.scaleX);
    var scaleYTo1 = (1 / this.scaleY);
    ctx.save();
    
    var ctxLeft = -( this.width / 2 ) + clipRect.strokeWidth;
		var ctxTop = -( this.height / 2 ) + clipRect.strokeWidth;
		var ctxWidth = clipRect.width - clipRect.strokeWidth;
		var ctxHeight = clipRect.height - clipRect.strokeWidth;

    ctx.translate( ctxLeft, ctxTop );
    
    ctx.rotate(degToRad(this.angle * -1));
    ctx.scale(scaleXTo1, scaleYTo1);
    ctx.beginPath();
    ctx.rect(
        clipRect.left - this.oCoords.tl.x,
        clipRect.top - this.oCoords.tl.y,
        clipRect.width,
        clipRect.height
    );
    ctx.closePath();
    ctx.restore();
}

var pugImg = new Image();
pugImg.onload = function (img) {    
    var pug = new fabric.Image(pugImg, {
        angle: 45,
        width: 500,
        height: 500,
        left: 230,
        top: 50,
        scaleX: 0.3,
        scaleY: 0.3,
        clipName: 'pug',
        clipTo: function(ctx) { 
            return...