JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
<canvas id="c" width="500" height="350"></canvas>
<br />
<input type="button" value="Rect Command" id="btn_rect" />
<input type="button" value="Delete Command" id="btn_delete" />
<input type="file" id="btn_upload" accept="image/*" />
CSS
#c {
border: 1px solid #333;
}
JavaScript
var eCommands;
(function(eCommands) {
eCommands[eCommands["None"] = 0] = "None";
eCommands[eCommands["Rect"] = 1] = "Rect";
eCommands[eCommands["Delete"] = 2] = "Delete";
})(eCommands || (eCommands = {}));
var Application = (function() {
function Application(canvas, rectButton, deleteButton, uploadButton) {
this._currentCommand = eCommands.None;
this._canvas = new fabric.Canvas(canvas);
this._rectButton = rectButton;
this._deleteButton = deleteButton;
this._uploadButton = uploadButton;
var cc = this._currentCommand;
var c = this._canvas;
var self = this;
this._drawRect = function() {
self._currentCommand = eCommands.Rect;
};
this._delete = function() {
c.clear();
};
this._executeCurrentCommand = function(e) {
switch (self._currentCommand) {
case eCommands.Rect:
var rect = new fabric.Rect({
left: c.getPointer(e.e).x - 10,
top: c.getPointer(e.e).y - 10,
fill: 'red',
width: 20,
height: 20
});
c.add(rect);
c.renderAll.bind(c);
break;
}
};
this._drawBackground = function(e) {
var reader = new FileReader();
reader.onload = function(event) {
c.setBackgroundImage(event.target.result, c.renderAll.bind(c), {});
};
reader.readAsDataURL(e.target.files[0]);
};
this._rectButton.addEventListener('click', this._drawRect, false);
this._deleteButton.addEventListener('click', this._delete, false);
this._uploadButton.addEventListener('change', this._drawBackground, false);
this._canvas.on('mouse:up', this._executeCurrentCommand);
}
return Application;
})();
var p = new Application(document.getElementById('c'),
document.getElementById('btn_rect'),
document.getElementById('btn_delete'),
document.getElementById('btn_upload'));