-
-
Save mahemoff/362627 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// TiddlyWiki 5 code from Jeremy Ruston | |
// Gives you a jQuery object that you can set width and height on, just as if it was an IMG tag. | |
var svgDoc = new DOMParser().parseFromString(svgText, | |
"application/xml").documentElement; | |
fixSVG(svgDoc.childNodes,generateIdPrefix()); | |
img = $(document.importNode(svgDoc, true)); | |
// IMPLEMENTATION | |
var fixSVG = function(childNodes,idPrefix) { | |
var urlPattern = /^\s*url\(\#([^\)]*)\)\s*$/ig; | |
var fixes = [ | |
{attr: "id", namespace: "", pattern: /^(.*)$/ig}, | |
{attr: "fill", namespace: "", pattern: urlPattern}, | |
{attr: "stroke", namespace: "", pattern: urlPattern}, | |
{attr: "href", namespace: "http://www.w3.org/1999/xlink", pattern: | |
/^#(.*)$/ig} | |
]; | |
for(var t=0; t<childNodes.length; t++) { | |
var node = childNodes[t]; | |
for(var a=0; a<fixes.length; a++) { | |
var fix = fixes[a]; | |
if(node.hasAttributeNS && node.hasAttributeNS(fix.namespace,fix.attr)) { | |
var v = node.getAttributeNS(fix.namespace,fix.attr); | |
fix.pattern.lastIndex = 0; | |
var match = fix.pattern.exec(v); | |
if(match) { | |
var replacement = (idPrefix + match[1]).replace("$","$$$$"); // | |
Make sure replacement string doesn't contain any single dollar signs | |
v = v.replace(match[1],replacement); | |
node.setAttributeNS(fix.namespace,fix.attr,v); | |
} | |
} | |
} | |
var children = node.childNodes; | |
if(children.length > 0) | |
fixSVG(children,idPrefix); | |
} | |
}; | |
var fixPrefix = 1; | |
// Generate a new, safe and unused ID prefix | |
var generateIdPrefix = function() { | |
return "svg_$&fix_" + (fixPrefix++).toString() + "_"; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment