-
Notifications
You must be signed in to change notification settings - Fork 354
Usage (2.x)
Viz.js is packaged in two parts: the main API (viz.js
) and the rendering script files (full.render.js
or lite.render.js
). The "full" rendering script file includes the Expat XML parser, for using HTML-like labels, and the NEATO layout engine.
The rendering script files can be loaded as Web Workers, required as CommonJS modules, or can be included directly using a <script>
tag.
Have a look at viz-examples for example projects.
const workerURL = 'path/to/full.render.js';
let viz = new Viz({ workerURL });
viz.renderSVGElement('digraph { a -> b }')
.then(function(element) {
document.body.appendChild(element);
})
.catch(error => {
// Create a new Viz instance (@see Caveats page for more info)
viz = new Viz({ workerURL });
// Possibly display the error
console.error(error);
});
In this case, the workerURL
option is the URL of one of the rendering script files included with the distribution. Requests to render graphs are passed to a Web Worker, and return promises that resolve when the worker finishes laying out and rendering the graph. Viz.js takes care of converting the SVG XML to a SVG element ready to be inserted into the document.
The ".render.js" suffix allows you indicate that a bundler such as Webpack or Rollup should not process the rendering script files, since they are fairly large (> 1 MB) and are meant to be used as workers in this case. Instead, the bundler should be configured to copy them and provide the final path of the file rather than a binding.
<script src="viz.js"></script>
<script src="full.render.js"></script>
<script>
var viz = new Viz();
viz.renderSVGElement('digraph { a -> b }')
.then(function(element) {
document.body.appendChild(element);
})
.catch(error => {
// Create a new Viz instance (@see Caveats page for more info)
viz = new Viz();
// Possibly display the error
console.error(error);
});
</script>
If no options are given, Viz.js will look for Viz.Module
and Viz.render
. These are added to the Viz
object by the render script file if it's defined on the global object. In this case, the Viz.js instance will still return promises, and the image and SVG element rendering functions can be used.
const Viz = require('viz.js');
const { Module, render } = require('viz.js/full.render.js');
let viz = new Viz({ Module, render });
viz.renderString('digraph { a -> b }')
.then(result => {
console.log(result);
})
.catch(error => {
// Create a new Viz instance (@see Caveats page for more info)
viz = new Viz({ Module, render });
// Possibly display the error
console.error(error);
});
In this case, the Module
and render
functions exported from the render script file are used. The Viz.js instance will still return promises, but they will resolve immediately.