Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>?

like image 885
MartinAnsty Avatar asked Feb 28 '14 10:02

MartinAnsty


3 Answers

By peering at the source-code, I think just doing a Snap('#object-id') would give you the SVG, instead of doing .node.contentDocument. This may be a recent improvement, but as of today, this is officially there in the code.

Here's the supporting source code: https://github.com/adobe-webplatform/Snap.svg/blob/5b17fca57cbc4f8a8fd9ddd55cea2511da619ecf/dist/snap.svg.js#L3182-L3184

like image 180
kumarharsh Avatar answered Oct 14 '22 04:10

kumarharsh


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

like image 42
Ian Avatar answered Oct 14 '22 05:10

Ian


Probably the best way is to use Snap's Element.node with an <object> tag if you are serving the svg from the same domain. E.g. you can't use it from a file system, you have to set up a local server (same-origin policy).

If you have

<object id="graph" data="somevectors.svg" type="image/svg+xml"></object>

Then you can just use this

var s = Snap(Snap("#graph").node); //wrap the element

Then select the svg elements with CSS selectors and mess around with them

var circle = s.select("#circle")
   .attr({
      opacity: .3
   });
like image 39
Nairi Narinyan Avatar answered Oct 14 '22 05:10

Nairi Narinyan