JointJS - Label Position

by Roman Bruckner

HTML

<html>
<head>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jointjs/3.7.2/joint.css" />
</head>
<body>
      <!-- content -->
      <div id="paper"></div>         

      <!-- dependencies -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.4.0/backbone.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jointjs/3.7.2/joint.js"></script>
    
    </body>
</html>

CSS

body {
  background: #cad8e3;
}

JavaScript

class Rectangle extends joint.dia.Element {

  defaults() {
    return {
      ...super.defaults,
      type: 'Rectangle',
      size: {
        width: 120,
        height: 40
      },
      attrs: {
        body: {
          fill: '#cad8e3',
          stroke: '#ed2637',
          strokeWidth: 2,
          width: 'calc(w)',
          height: 'calc(h)'
        },
        label: {
          fontSize: 14,
          fontFamily: 'sans-serif',
          fill: '#131e29',
        }
      }
    };
  }

  preinitialize() {
    this.markup = [{
      tagName: 'rect',
      selector: 'body'
    }, {
      tagName: 'text',
      selector: 'label'
    }];
  }
}
const namespace = {
  ...joint.shapes,
  Rectangle,
};

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

const paper = new joint.dia.Paper({
  el: document.getElementById('paper'),
  overflow: true,
  model: graph,
  async: true,
  sorting: joint.dia.Paper.sorting.APPROX,
  cellViewNamespace: namespace,
  background: {
    color: 'transparent'
  }
});

const textMargin = 5;

const rCenter = new Rectangle();
rCenter.attr('label', {
  text: 'Center',
  textVerticalAnchor: 'middle',
  textAnchor: 'middle',
  x: 'calc(w/2)',
  y: 'calc(h/2)'
});
rCenter.position(10, 30).addTo(graph);

const rAbove = new Rectangle();
rAbove.attr('label', {
  text: 'Above',
  textVerticalAnchor: 'bottom',
  textAnchor: 'middle',
  x: 'calc(w/2)',
  y: -textMargin
});
rAbove.position(10, 130);

const rBelow = new Rectangle();
rBelow.attr('label', {
  text: 'Below',
  textVerticalAnchor: 'top',
  textAnchor: 'middle',
  x: 'calc(w/2)',
  y: `calc(h + ${textMargin})`
});
rBelow.position(10, 230);

const rLeft = new Rectangle();
rLeft.attr('label', {
  text: 'Left',
  textVerticalAnchor: 'middle',
  textAnchor: 'end',
  x: -textMargin,
  y: 'calc(h/2)',
});
rLeft.position(200, 80);

const rRight = new Rectangle();
rRight.attr('label', {
  text: 'Right',
  textVerticalAnchor: 'middle',
  textAnchor: 'start',
  x: `calc(w +...