JSFiddle - React, Tailwind, and code Playground
by Subhasish2015
HTML
<canvas id="canvas" width=500 height=500></canvas>
JavaScript
var canvas1 = new fabric.Canvas('canvas');
var drawingMode = null;
var divPos = {};
var offset = $("#canvas").offset();
$(document).mousemove(function(e){
divPos = {
left: e.pageX - offset.left,
top: e.pageY - offset.top
};
});
drawingMode = "Rect";
freeDrawing = true;
//Declaring the variables
var isMouseDown=false;
var refRect;
var width = 0;
var height = 0;
//Setting the mouse events
canvas1.on('mouse:down',function(event){
if(drawingMode != "Rect") return;
//Defining the procedure
isMouseDown=true;
//Getting yhe mouse Co-ordinates
//Creating the rectangle object
if(freeDrawing) {
var rect=new fabric.Rect({
left:divPos.left,
top:divPos.top,
width:0,
height:0,
stroke:'red',
strokeWidth:3,
fill:''
});
refRect=rect; //**Reference of rectangle object
}
});
canvas1.on('mouse:move', function(event){
// Defining the procedure
if(drawingMode != "Rect") return;
if(!isMouseDown)
{
return;
}
//Getting yhe mouse Co-ordinates
if(freeDrawing) {
var posX=divPos.left;
var posY=divPos.top;
width = Math.abs((posX-refRect.get('left')));
height = Math.abs((posY-refRect.get('top')));
refRect.setWidth(width);
refRect.setHeight(height);
// canvas1.renderAll(refRect);
}
});
canvas1.on('mouse:up',function(){
//alert("mouse up!");
if(drawingMode != "Rect") return;
if(freeDrawing && (width > 10) && (height > 10)) {
...