Drawing lines with a mouse

by swesh

HTML

<script src="https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c" width="400" height="400" style="border:1px solid #ccc"></canvas>

<button id="selec" >Turn off drawing</button>
<button id="clear">Clear All</button>

JavaScript

var canvas = new fabric.Canvas('c', { selection: false });
$("#selec").click(function(){
    canvas.isDrawingMode = false;
    canvas.selection= true;
    canvas.off('mouse:down');
    canvas.off('mouse:move');
    canvas.off('mouse:up');
    $(this).text("Drawing mode is off");
})
$("#clear").on("click", function() {
    canvas.clear();
});
var line, isDown;



canvas.on('mouse:down', function(o){
  isDown = true;
  var pointer = canvas.getPointer(o.e);
  var points = [ pointer.x, pointer.y, pointer.x, pointer.y ];
  line = new fabric.Line(points, {
    strokeWidth: 1,
    fill: 'red',
    stroke: 'red',
    originX: 'center',
    originY: 'center'
  });
    line.setControlsVisibility({
        ml:false,
        mr:false,
        mt:false,
        mb:false,
         tr: false,
        bl:false
        
    });
  canvas.add(line);   
    
});

canvas.on('mouse:move', function(o){
  if (!isDown) return;
  var pointer = canvas.getPointer(o.e);
  line.set({ x2: pointer.x, y2: pointer.y });
  line.setCoords();
  canvas.renderAll();
});

canvas.on('mouse:up', function(o){
  isDown = false;
});
canvas.on({
    'object:selected': function() {
        console.log(this._activeObject);
        var activeObject = this._activeObject;
        var slopeOfLine = Math.atan(Math.abs((activeObject.y2-activeObject.y1)/(activeObject.x2-activeObject.x1)));
        console.log(slopeOfLine*(180/Math.PI));
    }
});