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 elementSnap(css selector)
- Same as above, but with a selector rather than a direct referenceIs it possible to create a Snap object from either an SVG embedded as either an<object>
element or a <img>
?
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
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
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With