Appearance
Badge
This example shows how to add Badges to nodes. Nodes can have up to 4 badges (top left, top right, bottom left, bottom-right). Badges have a stroke, a background (color or image) and can contain text or icons.
ts
import Ogma, { Node } from '@linkurious/ogma';
const COLORS = [
'#965E04',
'#C89435',
'#F7A456',
'#AFCF8A',
'#7B39DE',
'#B095C0',
'#D24556',
'#93C2FA',
'#9DB09E',
'#F8C821'
];
const placeholder = document.createElement('span');
document.body.appendChild(placeholder);
placeholder.style.visibility = 'hidden';
// helper routine to get the icon HEX code
function getIconCode(className: string) {
placeholder.className = `icon-${className}`;
const code = getComputedStyle(placeholder, ':before').content;
return code[1];
}
const ICONS = [
getIconCode('mic'),
getIconCode('mic-off'),
getIconCode('shield-half'),
getIconCode('keyboard'),
getIconCode('circle-help'),
getIconCode('info'),
getIconCode('flag'),
getIconCode('settings')
];
const ogma = new Ogma({
container: 'graph-container'
});
function getColor(node: Node) {
const id = +node.getId();
return COLORS[id % COLORS.length];
}
// Rules to specify the node style. Functions must be deterministic.
ogma.styles.addRule({
nodeAttributes: {
color: getColor,
text: {
content: n => 'Node ' + n.getId(),
font: 'IBM Plex Sans'
},
radius: 15,
badges: {
bottomRight: {
color: '#fff',
text: {
font: 'Lucide', // Use FontAwesome icons.
color: '#336', // Use the node color.
// Retrieve the icon based on the node id.
content: n => ICONS[+n.getId() % ICONS.length]
},
stroke: {
color: getColor, // Use the node color
width: 2
},
scale: 0.45 // Scale the icon
}
}
},
nodeDependencies: {
self: { attributes: 'all' }
}
});
// Generate a random graph
const graph = await ogma.generate.random({ nodes: 10, edges: 0 });
await ogma.setGraph(graph);
await ogma.layouts.force({ locate: true });
// Change the badge of a single node: use a
// background image and some text content.
ogma.getNode('0')!.setAttributes({
badges: {
bottomRight: {
image: 'flags/fr.svg',
text: {
font: 'Arial',
style: 'bold',
content: 'FR',
color: 'black'
}
}
}
});
html
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<link type="text/css" rel="stylesheet" href="styles.css" />
</head>
<body>
<div id="graph-container"></div>
<script src="index.ts"></script>
</body>
</html>
css
#graph-container {
top: 0;
bottom: 0;
left: 0;
right: 0;
position: absolute;
margin: 0;
overflow: hidden;
}