JointJS: Custom label position

by Roman Bruckner

HTML

<html>

  <head>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" />
  </head>

  <body>
    <!-- content -->
    <div id="paper" style="margin: 20px;"></div>

    <!-- dependencies -->
    <script src="https://cdn.jsdelivr.net/npm/@joint/[email protected]/dist/joint.min.js"></script>
  </body>

</html>

JavaScript

const graph = new joint.dia.Graph({}, {
    cellNamespace: joint.shapes
});

const paper = new joint.dia.Paper({
    el: document.getElementById('paper'),
    width: 800,
    height: 900,
    model: graph,
    cellViewNamespace: joint.shapes,
    interactive: {
        labelMove: true
    },
    snapLabels: true,
    gridSize: 10,
    async: true,
    sorting: joint.dia.Paper.sorting.APPROX,
    linkPinning: false,
    defaultRouter: {
        name: 'rightAngle',
        args: {
            sourceDirection: 'right',
            targetDirection: 'left',
        }
    },
    linkView: joint.dia.LinkView.extend({
        _getLabelTransformationMatrix: function() {
            const [polyline] = this.getConnection().toPolylines();
            polyline.simplify();
            const line = new g.Line(polyline.points.at(-2), polyline.points.at(-1));
            const midPoint = line.midpoint();
            const matrix = (new DOMMatrix()).translate(midPoint.x, midPoint.y);
            return matrix;

        },

    })
});

// Example

const el1 = new joint.shapes.standard.Rectangle({
    position: {
        x: 10,
        y: 270
    },
    size: {
        width: 100,
        height: 90
    },
    attrs: {
        label: {
            text: 'A'
        }
    }
});
const el2 = new joint.shapes.standard.Rectangle({
    position: {
        x: 400,
        y: 170
    },
    size: {
        width: 100,
        height: 90
    },
    attrs: {
        label: {
            text: 'B'
        }
    }
});

const l1 = new joint.shapes.standard.Link({
    source: {
        id: el1.id
    },
    target: {
        id: el2.id
    },
    attrs: {
        line: {
            strokeWidth: 3
        }
    },
    labels: [{
        markup: [{
            tagName: 'rect',
            selector: 'labelBody'
        }],
        attrs: {
            labelBody: {
                fill: 'lightgreen',
                stroke: 'black',
                strokeWidth: 2,
                x: -15,
           ...