Search code examples
javascriptsnap.svg

Creating a Snap.svg object from an <object> element


The documentation for Snap.svg's Snap() function lists three possible ways of creating a Snap object.

  • Snap(width, height) - Creates a new, blank canvas of given dimensions.
  • Snap(svg element) - Create a Snap canvas from an existing, inline SVG element
  • Snap(css selector) - Same as above, but with a selector rather than a direct reference

Is it possible to create a Snap object from either an SVG embedded as either an<object> element or a <img>?


Solution

  • Only thing I can come up with that may sort of work, is using something like the object tag, with contentDocument (may need to check support, but Snap isn't really aimed at old browsers anyway).

    I think the svg image will have to be local to the file though, so remote calls to images I don't think would work (or maybe with some amended server settings), so I couldn't get it working on a fiddle to show, just with a test url below, so the code would be something like...

    in html...

    <object id="tux" data="Dreaming_Tux.svg" width="600" height="600" type="image/svg+xml"></object>
    

    then js....

    var tux = Snap("#tux");
    var tuxContent = tux.node.contentDocument;   /// grab the referenced content
    
    var sTux = Snap( tuxContent.firstChild );    /// snapify it
    var tuxPaths = sTux.selectAll('path');       /// use snaps selector to grab elements
    
    tuxPaths.forEach( function( el ) { el.attr({ opacity: 0.2 }) });
    

    testing example here