Polygon Clipping

Sample test Polygon Clipping with JSClipper

by Samuel Price

HTML

<script src="http://jsclipper.sourceforge.net/6.1.3.2/clipper.js"></script>
    <h2>Javascript Clipper Library / Boolean operations / Canvas example</h2>
    This page shows an example of boolean operations on polygons and drawing them on html5 canvas as bitmap images.
    <br><br>
    <div id="canvascontainer">
      <div id="desc0"></div>
      <canvas id="canvas0"></canvas>

    </div>
    <div id="desc"></div>

CSS

h3{ margin-bottom:2px}
body,th,td,input,legend,fieldset,p,b,button,select,textarea {
    font-size: 14px;
    font-family: Arial, Helvetica, sans-serif;
}

JavaScript

function drawPath(ctx, path, offset){
var scale = .3
  for(j = 0; j < path.length; j++) {   
    x = path[j].X * scale  + offset;
    y = path[j].Y * scale;
    if (!j) ctx.moveTo(x, y);
    else ctx.lineTo(x, y);
  }

}
function draw() {    
var clipPath = [{X:100,Y:80},{X:150,Y:160},{X:300,Y:80}];
var subjPath = [{X:100,Y:80},{X:300,Y:80},{X:300,Y:200}, {X:100,Y:200}];


/*     [{X:100,Y:80},{X:150,Y:160},{X:300,Y:80}], */
/*     [{X:120,Y:100},{X:200,Y:100},{X:200,Y:140},{X:120,Y:140}],
    [{X:100,Y:160},{X:180,Y:160},{X:180,Y:200},{X:100,Y:200}],
    [{X:80,Y:100},{X:160,Y:100},{X:160,Y:140},{X:80,Y:140}] */
/*                       ];     */
    var index = 0;



        
        // Scale Up Path
        var scale = 100;
        ClipperLib.JS.ScaleUpPath(subjPath, scale);
        ClipperLib.JS.ScaleUpPath(clipPath, scale);
        
        // Add Path to ClipperLib
        var cpr = new ClipperLib.Clipper();
        cpr.AddPath(subjPath, ClipperLib.PolyType.ptSubject, true);
        cpr.AddPath(clipPath, ClipperLib.PolyType.ptClip, true);
        
        var polyCallDict = {
            clipType: ClipperLib.ClipType.Difference,
            subjectInputs: [{data: subjPath, closed : true}],
            clipInputs: [{data: clipPath}],
            subjectFillType: ClipperLib.PolyFillType.EvenOdd
			  }
  			var solution_paths = cpr.clipToPaths(polyCallDict)
        
        var subject_fillType = ClipperLib.PolyFillType.pftNonZero;
        var clip_fillType = ClipperLib.PolyFillType.pftNonZero;
        var clipType = ClipperLib.ClipType.ctDifference;
                
        var  canvas_str, canvas, des, ctx, i, i2, j, x, y;

/*         solution_paths = new ClipperLib.Paths();
        cpr.Execute(clipType, solution_paths, subject_fillType, clip_fillType); */
        
        canvas = document.getElementById("canvas" + index);
        canvas.width = canvas.height = 900;
        ctx = canvas.getContext("2d");
        ctx.fillStyle = "red";
       ...