JointJS: Custom Attribute To Set CSS Property
by Roman Bruckner
HTML
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jointjs/3.7.4/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.4/joint.js"></script>
</body>
</html>
CSS
.joint-element:hover .circle-body {
fill: var(--color);
}
.joint-element:hover .circle-icon {
stroke: white;
}
JavaScript
const Circle = joint.dia.Element.define('Circle', {
// defaults
size: { width: 100, height: 100 },
markup: [{
tagName: 'ellipse',
selector: 'body'
}, {
tagName: 'path',
selector: 'cross'
}],
attrs: {
root: {
cssProperty: { name: 'color', value: 'red' },
stroke: 'red',
},
body: {
class: 'circle-body',
fill: '#FFFFFF',
strokeWidth: 3,
rx: 'calc(w / 2)',
ry: 'calc(h / 2)',
cx: 'calc(w / 2)',
cy: 'calc(h / 2)',
},
cross: {
class: 'circle-icon',
d: 'M calc(w / 2) 10 L calc(w / 2) calc(h - 10) M 10 calc(h / 2) L calc(w - 10) calc(h / 2)',
strokeWidth: 10,
}
}
}, {
// prototype properties
}, {
// static properties
attributes: {
cssProperty: {
set: function(property, refBBox, node, attrs) {
node.style.setProperty(`--${property.name}`, property.value);
}
}
}
});
const namespace = { Circle };
const graph = new joint.dia.Graph({}, { cellNamespace: namespace });
const paper = new joint.dia.Paper({
el: document.getElementById('paper'),
width: 800,
height: 600,
model: graph,
async: true,
sorting: joint.dia.Paper.sorting.APPROX,
cellViewNamespace: namespace,
});
const c1 = new Circle({
position: { x: 100, y: 100 },
});
const c2 = new Circle({
position: { x: 400, y: 100 },
attrs: {
root: {
cssProperty: { name: 'color', value: 'blue' },
stroke: 'blue',
},
}
});
graph.addCells([c1, c2]);