JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/flatly/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.6/fabric.min.js"></script>
<div class="jumbotron text-center">
<h1>Web Canvas UML</h1>
</div>
<div class="text-center">
<button class="btn btn-primary" onclick="addRect()">Rectangle</button>
<button class="btn btn-primary" onClick="addChild()">Add Child</button>
<button class="btn btn-primary" onClick="deleteObject()">Delete Object</button>
</div>
<br/><br/>
<div class="container text-center">
<canvas id="canvas"></canvas>
</div>
CSS
#canvas {
background-color: gray;
width: 100% !important;
height: 500px;
}
canvas {
width: 100% !important;
}
.canvas-container {
height: 500px;
width: 100% !important;
}
JavaScript
/**
*
*/
const REC_WIDTH = 60;
const REC_HEIGHT = 30;
const TRI_WIDTH = 10;
const TRI_HEIGHT = 10;
var canvas = new fabric.Canvas('canvas');
resizeCanvas();
// we need this here because this is when the canvas gets initialized
['object:moving', 'object:scaling'].forEach(addChildMoveLine);
function addRect() {
var rect = new fabric.Rect({
left: 100,
top: 100,
fill: 'blue',
width: REC_WIDTH,
height: REC_HEIGHT
});
canvas.add(rect);
}
function addChild() {
if(canvas.getActiveObject() == null)
{
return;
}
canvas.addChild = {
start: canvas.getActiveObject()
};
// for when addChild is clicked twice
canvas.off('object:selected', addChildLine);
canvas.on('object:selected', addChildLine);
}
function deleteObject() {
var object = canvas.getActiveObject();
// remove lines (if any)
if (object.addChild) {
if (object.addChild.lines)
// step backwards since we are deleting
for (var i = object.addChild.lines.length - 1; i >= 0; i--) {
var line = object.addChild.lines[i];
line.triangle.remove();
line.addChildRemove();
line.remove();
}
}
object.remove();
}
function calcArrowAngle(x1, y1, x2, y2) {
var angle = 0,
x, y;
x = (x2 - x1);
y = (y2 - y1);
if (x === 0) {
angle = (y === 0) ? 0 : (y > 0) ? Math.PI / 2 : Math.PI * 3 / 2;
} else if (y === 0) {
angle = (x > 0) ? 0 : Math.PI;
} else {
angle = (x < 0) ? Math.atan(y / x) + Math.PI : (y < 0) ? Math.atan(y / x) + (2 * Math.PI) : Math.atan(y / x);
}
return (angle * 180 / Math.PI + 90);
}
function addChildLine(options) {
canvas.off('object:selected', addChildLine);
// add the line
var fromObject = canvas.addChild.start;
var toObject = options.target;
var from = fromObject.getCenterPoint();
var to =...