Polygon Clipping
Sutherland-Hodgman polygon clipping
HTML
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<script src=" https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.11/fabric.js"></script>
<canvas id="c" width="500" height="350" style="border:1px solid #ccc"></canvas>
JavaScript
var canvas = new fabric.Canvas('c', { selection: false });
var polygons = [];
var ctx = canvas.contextContainer;
var poly2 = new fabric.Polygon([{'x': 125,'y':75},{'x': 110,'y':150}, {'x': 200,'y':110}
], {
fill: '#FFFFAA',
fillRule: 'evenodd',
strokeWidth: 1,
stroke: 'black',
selectable: false
});
var poly1 = new fabric.Polygon([{'x': 30,'y':15}, {'x': 250,'y':110},{'x': 125,'y':190}
], {
fillRule: 'evenodd',
fill: '#FFFFAA',
strokeWidth: 1,
stroke: 'black',
selectable: false });
canvas.add(poly1);
canvas.add( poly2);
ctx.beginPath();
//outer shape, any direction, this sample is clockwise
ctx.moveTo(400,20);
ctx.lineTo(450,200);
ctx.lineTo(200,200);
ctx.closePath();
//inner shape (hole), any direction, this sample is clockwise
//ctx.fillStyle = "green";
ctx.moveTo(350,15);
ctx.lineTo(500,110);
ctx.lineTo(200,190);
ctx.closePath();
//fill
ctx.fillStyle = "green";
ctx.fill('evenodd'); //for firefox 31+, IE 11+, chrome