JointJS extend Standard Rectangle shape to include a text element

172 Views Asked by At

How do we extend Standard shape to add and extra SVGTextElement ? is it possible at all or does it require custom shape ?

1

There are 1 best solutions below

4
James On

Yes, it's possible to extend a standard shape. You could do something like the following to extend the standard.Rectangle with a 2nd label/text element.

import { dia, shapes, util } from "jointjs";

class Rect extends shapes.standard.Rectangle {
      defaults() {
          return {
              ...super.defaults,
              type: 'Rect',
              attrs: {
                  body: {
                      width: 'calc(w)',
                      height: 'calc(h)',
                      fill: 'white',
                      strokeWidth: 2,
                      stroke: 'black'
                  },
                  label: {
                      text: '1st',
                      textVerticalAnchor: 'middle',
                      textAnchor: 'middle',
                      fontSize: 14,
                      x: 'calc(w/2)',
                      y: 'calc(h/2)'
                   },
                   secondaryLabel: {
                      text: '2nd',
                      textVerticalAnchor: 'middle',
                      textAnchor: 'middle',
                      fontSize: 14,
                      x: 'calc(w/2)',
                      y: 'calc(h/1.25)'
                  }
              }
         };
     }
      
     preinitialize() {
         this.markup = util.svg/* xml */ `
             <rect @selector='body' />
             <text @selector='label' />
             <text @selector='secondaryLabel' />
         `;
     }
}

const namespace = {
  Rect,
  ...shapes
};

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

const rect = new Rect();
rect.position(300, 10);
rect.resize(100, 100);
rect.addTo(graph);

You can learn more about extending/creating custom elements in the following tutorials:

https://resources.jointjs.com/tutorial/custom-elements

https://resources.jointjs.com/tutorial/ts-shape