Appearance
Exporting graphs in Node.js
Ogma can run on Node.js, and with the right packages can perform PNG and SVG export:
canvas@2.0.0
or greater for PNG exportxmldom@0.1.27
or greater for SVG export- Tested on Node.js 8.12.0
To get started, take a look at the Node.js export project template.
Example of PNG export
js
const fs = require('fs');
const Ogma = require('@linkurious/ogma');
const Canvas = require('canvas');
// Specify the canvas dependency so Ogma can use it
Ogma.libraries.canvas = Canvas;
// Register the font that we're going to use
Canvas.registerFont('arial.ttf', { family: 'Arial' });
// Create an instance of Ogma
const ogma = new Ogma();
// Add a node
ogma.addNode({
attributes: {
shape: 'pentagon',
color: 'orange',
text: {
content: 'Exported in Node.js',
font: 'Arial',
position: 'center'
}
}
});
// Export to a 200x200 PNG
ogma.export
.png({ width: 200, height: 200, background: 'white' })
.then(function (base64Str) {
// Remove the base 64 header
base64Str = base64Str.replace(/^data:image\/png;base64,/, '');
// Write the image to the disk
fs.writeFileSync('graph.png', base64Str, 'base64');
});
Exporting text in PNG
All used fonts must be specified with Canvas.registerFont()
, before creating the first instance of Ogma:
js
Canvas.registerFont('arial.ttf', { family: 'Arial' });
Possible warning
When exporting text on Linux, you might get the warning Fontconfig error: Cannot load default config file
. As explained here, it simply indicates that you don't have any fonts on your system. If all your fonts are registered through registerFont
you can ignore the warning.
Example of SVG export
js
const fs = require('fs');
const Ogma = require('@linkurious/ogma');
const xmldom = require('@xmldom/xmldom');
// Specify the xmldom dependency so Ogma can use it
Ogma.libraries.xmldom = xmldom;
// Create an instance of Ogma
const ogma = new Ogma();
// Add a node
ogma.addNode({
attributes: {
shape: 'pentagon',
color: 'orange',
text: {
content: 'Exported in Node.js',
font: 'Arial',
position: 'center'
}
}
});
// Export to a 200x200 SVG
ogma.export
.svg({ width: 200, height: 200, background: 'white' })
.then(function (svg) {
// Write the image to the disk
fs.writeFileSync('graph.svg', svg, 'utf8');
});