Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Snap.load() external SVG fails to Load

PROBLEM: I'm using Snap.svg to create some basic interactive graphics, but for some reason I can't get my external SVG file to load using Snap.load(). I've pulled code straight from the tutorial at snap.io and checked and double-checked the docs. My SVG file renders in the browser fine, it just doesn't display inside the Snap SVG. Other shapes (i.e. not pulled in using Snap.load() ) do display.

CODE: I've boiled my example down to the most simple HTML and SVG files imaginable, and the Snap.load() method still isn't working for me. Does anyone see what I'm missing?

HTML:

<head>
  <style media="screen">
            #svg {
                width: 300px;
                height: 300px;
            }
  </style>
  <script src="snap.svg-min.js"></script>
  <meta charset=utf-8 />
</head>
<body>
  <svg id="svg"></svg>
  <script type="text/javascript">
    var s = Snap("#svg");
    Snap.load("svgtest.svg");
  </script>
</body>

SVG (originally exported from Illustrator):

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="100px" height="100px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve">
<rect x="14" y="33" fill="#2BB673" width="70" height="30"/>
</svg>

UPDATE: Updated the code as per @Ian's suggestion -

var s = Snap("#svg");
Snap.load("http://www.w3.org/TR/SVG/images/struct/Use01.svg", onSVGLoaded ) ;

function onSVGLoaded( data ){ 
    s.append( data );
}

- but still no display of external SVG. I tried using an SVG from w3.org just to be sure it wan't a problem with the file itself or my domain.

like image 622
Marcatectura Avatar asked Nov 12 '13 09:11

Marcatectura


2 Answers

The load function takes a callback, as loading can take some time. So I think you would do something like the following...

var s = Snap("#svg");
Snap.load("svgtest.svg", onSVGLoaded ) ;

function onSVGLoaded( data ){ 
    s.append( data );
}

Edit: There may be some access control issues if not accessing from the same server as the script, check the console log for any errors.

like image 158
Ian Avatar answered Nov 11 '22 17:11

Ian


I was having exactly this problem in Internet Explorer only, and it turned out to be because the SVG file I was loading in was a minified one from which the doctype had been removed. Other browsers were ok without the doctype, but leaving the doctype in fixed the problem in IE as well:

<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

In case, like me, you're using Grunt to minify SVGs, you can leave the doctype in by adding the following option to your Gruntfile:

svgmin: {
    options: {
        plugins: [
            { removeDoctype: false }
        ]
    }
    // etc...
}
like image 29
Nick F Avatar answered Nov 11 '22 18:11

Nick F