FabricJS clipTo Group

FabricJS clipTo Group workarounds

by freelast

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.3/fabric.min.js"></script>
<canvas id="designer" width="600" height="600"></canvas>
<div class="t-shirt">

</div>

CSS

#designer {
  border: 1px solid #333
}

.t-shirt {
  z-index: -1;
  top: 100px;
  left: 81px;
  display: block;
  position: absolute;
  width: 438px;
  height: 428px;
  background-image:...

JavaScript

var canvas = new fabric.Canvas('designer',{controlsAboveOverlay: true});
	
		var circle = new fabric.Circle({
			radius: 100,
			fill: '#ccc',
			scaleY: 0.5,
			originX: 'center',
			originY: 'center'
		});

		var circle2 = new fabric.Circle({
			radius: 50,
			fill: '#ccc',
			left: 100
		});

		var group = new fabric.Group([circle, circle2], {
			left: 190,
			top: 500,
			angle: -90,
			
			canvas:{
			/* workaround with bug in fabric.js to keep dependencies default
			// this.canvas.preserveObjectStacking throws an error because
			// this.canvas is not defined */
			}
		});

		if (!group.canvas) {
			/* workaround with bug in fabric.js to keep dependencies default
			// this.canvas.preserveObjectStacking throws an error because
			// this.canvas is not defined */
			group.canvas = {};
		};

		canvas.clipTo = function (ctx) {

			var skip = false
				// Workaround to make possible 
				// making clipTo with 
				// fabric.Group 
				var oldBeginPath = ctx.beginPath;
				ctx.beginPath = function () {
					if (!skip) {
						oldBeginPath.apply(this, arguments);
						skip = true;
						setTimeout(function () {
							skip = false;
						}, 0);
					}
				}
				
				setTimeout(function() {
					ctx.beginPath = oldBeginPath;
				},0);
	
			group.render(ctx)
		};

		fabric.Image.fromURL('https://www.google.com.ua/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png', function (oImg) {
			//oImg.set('left', PosX).set('top',PosY);
			canvas.add(oImg);
			canvas.renderAll();
		}, {
			"left": 200,
			"top": 200
		});