fabric.js - draw a dynamic polygon with mouse click

http://stackoverflow.com/questions/31372456/fabric-js-cannot-get-bounding-box-to-match-its-dynamic-object

by Anand Rathod

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

<button id="poly"  title="Draw Polygon" ">Draw Polygon </button>


<label style="color:blue"><b>Press double click to close shape and stop</b></label>
<canvas id="canvas-tools" class="canvas" width="500" height="500"></canvas>

CSS

.canvas {
    border: 1px solid black;
}

JavaScript

var roof = null;
    var roofPoints = [];
    var lines = [];
    var lineCounter = 0;
    var drawingObject = {};
    drawingObject.type = "";
    drawingObject.background = "";
    drawingObject.border = "";

    function Point(x, y) {
        this.x = x;
        this.y = y;
    }
    

    $("#poly").click(function () {
        if (drawingObject.type == "roof") {
            drawingObject.type = "";
            lines.forEach(function(value, index, ar){
                 canvas.remove(value);
            });
            //canvas.remove(lines[lineCounter - 1]);
            roof = makeRoof(roofPoints);
            canvas.add(roof);
            canvas.renderAll();
        } else {
            drawingObject.type = "roof"; // roof type
        }
    });


    // canvas Drawing
var canvas = new fabric.Canvas('canvas-tools');
    var x = 0;
    var y = 0;
    
    fabric.util.addListener(window,'dblclick', function(){ 
            drawingObject.type = "";
            lines.forEach(function(value, index, ar){
                 canvas.remove(value);
            });
            //canvas.remove(lines[lineCounter - 1]);
            roof = makeRoof(roofPoints);
            canvas.add(roof);
            canvas.renderAll();
      
        console.log("double click");
        //clear arrays
         roofPoints = [];
         lines = [];
         lineCounter = 0;
        
    });

    canvas.on('mouse:down', function (options) {
        if (drawingObject.type == "roof") {
            canvas.selection = false;
            setStartingPoint(options); // set x,y
            roofPoints.push(new Point(x, y));
            var points = [x, y, x, y];
            lines.push(new fabric.Line(points, {
                strokeWidth: 3,
                selectable: false,
                stroke: 'red'
            }).setOriginX(x).setOriginY(y));
            canvas.add(lines[lineCounter]);
            lineCounter++;
            canvas.on('mouse:up', function (options) {
               ...