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://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body>
<canvas id="c" width="400" height="400" style="border:1px solid #ccc"></canvas>
<br><button id="select">Selection mode</button>
<button id="draw">Drawing mode</button>
<button id="delete">Delete selected object(s)</button>
</body>
</html>
JavaScript
var line, isDown,mode;
var canvas = new fabric.Canvas('c');
$("#select").click(function(){
mode="select";
canvas.selection=true;
canvas.perPixelTargetFind = true;
canvas.targetFindTolerance = 4;
canvas.renderAll();
});
$("#draw").click(function(){
mode="draw";
});
$("#delete").click(function(){
deleteObjects();
});
// Adding objects to the canvas...
canvas.on('mouse:down', function(o){
isDown = true;
var pointer = canvas.getPointer(o.e);
var points = [ pointer.x, pointer.y, pointer.x, pointer.y ];
if(mode=="draw"){
line = new fabric.Line(points, {
strokeWidth: 5,
fill: 'red',
stroke: 'red',
originX: 'center',
originY: 'center',
selectable: false,
targetFindTolerance: true
});
canvas.add(line);}
});
canvas.on('mouse:move', function(o){
if (!isDown) return;
var pointer = canvas.getPointer(o.e);
if(mode=="draw"){
line.set({ x2: pointer.x, y2: pointer.y });
canvas.renderAll(); }
});
canvas.on('mouse:up', function(o){
isDown = false;
});
// select all objects
function deleteObjects(){
var activeObject = canvas.getActiveObject(),
activeGroup = canvas.getActiveGroup();
if (activeObject) {
if (confirm('Are you sure?')) {
canvas.remove(activeObject);
}
}
else if (activeGroup) {
if (confirm('Are you sure?')) {
var objectsInGroup = activeGroup.getObjects();
canvas.discardActiveGroup();
objectsInGroup.forEach(function(object) {
canvas.remove(object);
});
}
}
}