[fabricJS] Mask editor

by Kris

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.4/fabric.min.js"></script>
<p>
  <button type="button" id="clear">Clear</button>
</p>
<p>
  Drawing: <input type="checkbox" id="drawing">
   | Brush Size: <input type="range" id="size" min="1" max="150" step="1" value="25">
</p>
<p>
  <button type="button" id="blb">--Layer</button>
  <button type="button" id="bld">-Layer</button>
  Layer: <span id="layer">0</span>
  <button type="button" id="blu">+Layer</button>
  <button type="button" id="blt">++Layer</button>
</p>
<div id="cont">
  <canvas id="img" width="500" height="500"></canvas>
  <canvas id="mask" width="500" height="500"></canvas>
  <canvas id="edit" width="500" height="500"></canvas>
  <canvas id="cursor" width="500" height="500"></canvas>
</div>

CSS

#cont {
  position: relative;
  width: 500px;
  height: 500px;
}

canvas {
  border: 1px solid;
}

#cont canvas, .canvas-container {
  position: absolute!important;
  left: 0!important;
  top: 0!important;
  width: 100%!important;
  height: 100%!important;
}

#cursor {
  pointer-events: none!important;
}

JavaScript

console.clear();
//load image to bottom layer
fabric.Image.fromURL("http://www.inf.fu-berlin.de/lehre/SS02/19541-V/lena_gray.gif", function (oImg) {
    oImg.set({
    		originX: "left",
        originY: "top",
        width: img.width,
        height: img.height,
        selectable: false
    });
    new fabric.Canvas("img", {selection: false}).add(oImg).renderAll();
});

// return the position of a pixel in the imageDataArray of the canvas
HTMLCanvasElement.prototype.getPixelPosition = function (x, y) {
	return (y * this.width + x) * 4;
};

fabric.Object.prototype.getLayerIndex = function () {
	return this.canvas.getObjects().indexOf(this);
};

fabric.Object.prototype.setFillOpacity = function (_opacity) {
  var fill = this.fill.split(",");
  fill[fill.length-1] = Math.min(1, Math.max(0, _opacity)) + ")";
  this.fill = fill.join(",");
};

fabric.FreeDrawingCursor = fabric.util.createClass(fabric.Circle, {

	type: "freeDrawingCursor",

	initialize: function (_options) {
  	//
  	_options = _options || {};
  	//
  	this.callSuper("initialize", fabric.util.object.extend({
    	originX: "center",
      originY: "center",
      left: 0,
      top: 0,
      radius: 50,
      fill: "transparent",
      stroke: "black"
    }, _options));
    
    this.on("added", this.moveOffscreen);
  },
  
  moveTo: function (x, y) {
  	this.canvas && this.set({
        left: x,
        top: y
      })
      .setCoords()
      .canvas.renderAll();
      
    return this;
  },
  
 	moveOffscreen: function () {
  	var _offset = -this.radius*2;
  	return this.moveTo(_offset, _offset);
  }
});

//change default settings
fabric.StaticCanvas.prototype.renderOnAddRemove = false;
fabric.Canvas.prototype.preserveObjectStacking = true;
fabric.Canvas.prototype.freeDrawingCursor = "none";
fabric.Canvas.prototype.rotationCursor =...