JointJS - Dynamic markup
by Roman Bruckner
HTML
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jointjs/3.5.5/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.5.5/joint.js"></script>
</body>
</html>
CSS
.joint-paper {
display: inline-block;
border: 1px solid gray;
}
JavaScript
joint.config.useCSSSelectors = false;
const graph = new joint.dia.Graph();
const paper = new joint.dia.Paper({
el: document.getElementById('paper'),
width: 800,
height: 800,
model: graph,
async: true,
interactive: { linkMove: false },
sorting: joint.dia.Paper.sorting.APPROX,
defaultConnectionPoint: {
name: 'boundary',
},
defaultRouter: {
name: 'normal'
}
});
class MyShape extends joint.dia.Element {
defaults() {
return {
...super.defaults,
type: 'MyShape',
image: true,
size: {
width: 100,
height: 80
},
attrs: {
body: {
width: 'calc(w)',
height: 'calc(h)',
fill: '#ffffff',
stroke: '#333333',
strokeWidth: 2
},
image: {
width: 'calc(w-2)',
height: 'calc(h-2)',
x: 2,
y: 2
},
label: {
text: 'Image',
textVerticalAnchor: 'middle',
textAnchor: 'middle',
x: 'calc(0.5*w)',
y: 'calc(0.5*h)',
fontSize: 14,
fill: '#333333'
}
}
};
}
initialize(...args) {
super.initialize(...args);
this.on('change', (_, opt) => {
if (this.hasChanged('image')) {
this.buildMarkup(opt);
}
});
this.buildMarkup();
}
buildMarkup(opt) {
const markup = [{
tagName: 'rect',
selector: 'body',
attributes: {
'stroke': 'none'
}
}];
const image = this.get('image');
if (image) {
markup.push({
...