Stroke Single Rectangle Side
Using `stroke-dasharray` to display the rectangle stroke at a single side.
by Roman Bruckner
HTML
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jointjs/3.4.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.4.4/joint.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,
async: true,
sorting: joint.dia.Paper.sorting.APPROX
});
const rect = new joint.shapes.standard.Rectangle({
position: {
x: 50,
y: 50
},
size: {
width: 100,
height: 100
},
attrs: {
body: {
fill: 'transparent'
}
}
});
joint.dia.attributes.strokeSide = {
offset: function(side, bbox, node) {
let dasharray = 'none';
const width = bbox.width;
const height = bbox.height;
switch (side) {
case 'left': {
dasharray = `0,${width * 2 + height},${height}`
break;
}
case 'right': {
dasharray = `0,${width},${height},${width + height}`
break;
}
case 'top': {
dasharray = `${width},${height * 2 + width}`
break;
}
case 'bottom': {
dasharray = `0,${width + height},${width},${height}`
break;
}
}
node.setAttribute('stroke-dasharray', dasharray);
}
}
// Alternatively when using ESM modules
// dia.Element.define(attributes, prototype, { attributes: { ... }})
rect.clone().attr({
body: {
strokeSide: 'bottom',
stroke: 'gray'
}
}).addTo(graph);
rect.clone().attr({
body: {
strokeSide: 'left',
stroke: 'red'
}
}).addTo(graph);
rect.clone().attr({
body: {
strokeSide: 'top',
stroke: 'blue'
}
}).addTo(graph);
rect.clone().attr({
body: {
strokeSide: 'right',
stroke: 'green'
}
}).addTo(graph);