How to align the svg with the viewBox for variable size tree

191 Views Asked by At

I have a D3JS tree and managed to download it as a SVG file. using the below code I managed to get the svg size and set the viewBox size accordingly (with 2% padding).

$('#download-SVG').click(function() {
    var svgElement = document.querySelector('svg');
    let {width, height} = svgElement.getBBox();
    var canvasWidth = Math.ceil(width + (width*.02));
    var canvasHeight = Math.ceil(height + (height*.02));

    var svgContent = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    svgContent.setAttribute('viewBox','0 0 '+canvasWidth+' '+canvasHeight);
    svgContent.setAttribute("width", "100%");
    svgContent.setAttribute("height", "100%");
    svgContent.setAttribute("preserveAspectRatio", "xMidYMid meet");
    svgContent.appendChild(svg.node()); 
    .
    .
    }

example of my svg file with small number of nodes is

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 308 295" width="100%" height="100%" preserveAspectRatio="xMidYMid meet"><g transform="translate(501,21)scale(0.7)"><path class="link" stroke="#ccc" fill="none" stroke-width="2px" d="M50,195C50,285 -115,285 -115,375"/>....</svg>

example of my svg file with many number of nodes is

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1368 3122" width="100%" height="100%" preserveAspectRatio="xMidYMid meet"><g transform="translate(449,36)scale(0.7)"><path class="link" stroke="#ccc" fill="none" stroke-width="2px" d="M352.5,555C352.5,645 22.5,645 22.5,735"/>...</svg>

My issue now, is that depending on the svg size which is dependent on the number of nodes expanded or collapsed, the svg and viewBox are always out of alignment. Expanding the tree to many nodes, shifts the svg to the left and collapsing to a small number of nodes, shifts the svg to the right.

I tried to set the x and y coordinates of the viewBox, but it never aligns exactly and make it align in all cases.

If I open the svg in InkScape and manually move the svg to the ViewBox, it fits nicely.

0

There are 0 best solutions below