'Translating cells (relative positioning) of an mxGraph from a container to another

For a work requirement that involves drawing a graph on the front end side, i use mxGraph.js library. My task consists among others to translate a graph from container1 to container2 (having different dimensions). Here's my code.

var graph = new mxGraph(document.getElementById('container1'));
var doc = mxUtils.createXmlDocument();
var node = doc.createElement('RootNode');
node.setAttribute('label', 'RootNode');
node.setAttribute('attribute1', 'value1');
mxGeometry.prototype.relative = true;
graph.insertVertex(graph.getDefaultParent(), null, node, $('#container1').width()/2 - 20, 40, 55, 22,"shape=rectangle");
var graphBis = new mxGraph(document.getElementById('container2'));
var enc = new mxCodec(mxUtils.createXmlDocument());
var node = enc.encode(graph.getModel());
var xmlString = mxUtils.getXml(node);
loadXMLGraph(graphBis, xmlString);
graphBis.center();
function loadXMLGraph(graphBis, xmlString) {
    var doc = mxUtils.parseXml(xmlString);
    var codec = new mxCodec(doc);
    codec.decode(doc.documentElement, graphBis.getModel());
    var elt = doc.documentElement.firstChild;
    var cells = [];
    while (elt != null) {
        var cell = codec.decode(elt)
        if (cell != undefined) {
            if (cell.id != undefined && cell.parent != undefined && (cell.id == cell.parent)) {
                elt = elt.nextSibling;
                continue;
            }

            cells.push(cell);
        }
        elt = elt.nextSibling;
    }

    graphBis.addCells(cells);
}

The HTML code is the following:

<html>
<head>
    <script type="text/javascript" src="./mxClient.js"></script>
</head>
    <body>
        <div class="container1">
            <div class="container2">
            </div>
        </div>
    </body>
</html>

CSS is not included here, but basically, container2 dimensions are smaller than of container1. I first try to encode the initial graph the equivalent XML document in order to reproduce it and put it inside container2 but the dimensions fail here and the graph root node finds itself out of boundaries in container2.

I tried using mxGraph.prototype.translateCell = function(cell,dx,dy) but the root node won't fit into container2.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source