Search code examples
javascriptjquerysnap.svg

Snapsvg copy path group from paper1 to paper2, fit inside responsive div


JSFIDDLE here of my issue. The Brazil region should load inside the modal.

Learning snap and trying to get a region from a world map and copy it onto a bootstrap modal. So click on a region, an image of the region itself is used on the modal.

I have achieved this but the shape is off to the right of the new canvas. I understand this is to do with viewbox and transform coords of the svg group cloned. How do I "fit shape to viewbox?

Here's my code for copying the image, which of course is not working.

var m = Snap('#world-map');
var d = Snap('#svg-region');
var regionSVG = m.select('#Brazil');
var p = Snap.parse(regionSVG);
var g = d.append(p);

This copies the SVG content OK, but it is not visible on the modal. On inspect I can see it off to the right. How do I center the Brazil svg group (for example) in the svg on the bootstrap?


Solution

  • First of all you probably want to either clone() the Brazil g element, or possibly use a 'use' element to reference it.

    In this case, I've simply cloned it, and added it to the modal svg...

    var p = regionSVG.clone();
    d.append(p);
    

    Then we can get the bounding box, and create a viewBox from that...

    var bb = regionSVG.getBBox();    
    var vb = bb.x + ' ' + bb.y + ' ' + bb.width + ' ' + bb.height;
    d.attr({ viewBox: vb})
    

    And hey presto, it should now have the Brazil map.

    You will probably want to do things like remove() on the element from the modal each time to clean up.

    jsfiddle