JSFiddle - React, Tailwind, and code Playground

by beewayne

HTML

<button onClick="newAnimation()">new Animation</button>
<button onClick="addRect()">Rectangle</button>
<button onClick="addCircle()">Circle</button>
<button onClick="addChild()">Add Child</button>
<button onClick="deleteObject()">Delete Object</button>
<canvas id="canvas" width="600" height="300"></canvas>

CSS

#canvas{
    background-color:gray
}

JavaScript

var canvas;
window.newAnimation = function () {
    canvas = new fabric.Canvas('canvas');

    // we need this here because this is when the canvas gets initialized
    ['object:moving', 'object:scaling'].forEach(addChildMoveLine)
}

window.addRect = function () {
    var rect = new fabric.Rect({
        left: 100,
        top: 100,
        fill: 'red',
        width: 20,
        height: 20,
    });
    canvas.add(rect);
}

window.addCircle = function () {
    var circle = new fabric.Circle({
        radius: 20, fill: 'green', left: 100, top: 100
    });
    canvas.add(circle);
}


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 = toObject.getCenterPoint();
    var line = new fabric.Line([from.x, from.y, to.x, to.y], {
        fill: 'red',
        stroke: 'red',
        strokeWidth: 5,
        selectable: false
    });
    canvas.add(line);
    // so that the line is behind the connected shapes
    line.sendToBack();

    // add a reference to the line to each object
    fromObject.addChild = {
        // this retains the existing arrays (if there were any)
        from: (fromObject.addChild && fromObject.addChild.from) || [],
        to: (fromObject.addChild && fromObject.addChild.to)
    }
    fromObject.addChild.from.push(line);
    toObject.addChild = {
        from: (toObject.addChild && toObject.addChild.from),
        to: (toObject.addChild && toObject.addChild.to) || []
    }
    toObject.addChild.to.push(line);

    // to remove line references when the line gets removed
    line.addChildRemove = function () {
        fromObject.addChild.from.forEach(function (e, i, arr) {
            if (e === line)
                arr.splice(i, 1);
        });
        toObject.addChild.to.forEach(function (e, i, arr) {
            if (e === line)
                arr.splice(i, 1);
   ...