Last active
August 26, 2016 14:52
-
-
Save EWhite613/6e866d3f2b16361749882aa6aaba6e0c to your computer and use it in GitHub Desktop.
svg.js conversion
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
[].forEach.call(document.querySelectorAll('use'), function (use) { | |
function replaceTargetWith( target, html ){ | |
/// find our target | |
var i, tmp, elm, last = target; | |
/// create a temporary div or tr (to support tds) | |
tmp = document.createElement(html.indexOf('<td')!=-1?'tr':'div'); | |
/// fill that div with our html, this generates our children | |
tmp.innerHTML = html; | |
/// step through the temporary div's children and insertBefore our target | |
i = tmp.childNodes.length; | |
/// the insertBefore method was more complicated than I first thought so I | |
/// have improved it. Have to be careful when dealing with child lists as | |
/// they are counted as live lists and so will update as and when you make | |
/// changes. This is why it is best to work backwards when moving children | |
/// around, and why I'm assigning the elements I'm working with to `elm` | |
/// and `last` | |
last = target; | |
while(i--){ | |
target.parentNode.insertBefore((elm = tmp.childNodes[i]), last); | |
last = elm; | |
} | |
/// remove the target. | |
target.parentNode.removeChild(target); | |
} | |
var | |
svg = use.parentNode, | |
url = use.getAttribute('xlink:href').split('#'), | |
url_root = url[0], | |
url_hash = url[1], | |
xhr = new XMLHttpRequest(); | |
if (!xhr.s) { | |
xhr.s = []; | |
xhr.open('GET', url_root); | |
xhr.onload = function () { | |
var x = document.createElement('x'), s = xhr.s; | |
x.innerHTML = xhr.responseText | |
xhr.onload = function () { | |
s.splice(0).map(function (array) { | |
var g = x.querySelector('#' + array[2]); | |
if (g) { | |
array[0].insertBefore(g,array[1]) | |
array[1].setAttribute('xlink:href','#' + array[2]) | |
var svg = array[0] | |
var xml = new XMLSerializer().serializeToString(svg) | |
var data = "data:image/svg+xml;base64," + btoa(xml) | |
var img = new Image() | |
img.setAttribute('src', data) | |
var box = g.getAttribute('viewBox'); | |
img.setAttribute('class', array[0].getAttribute('class')) | |
img.setAttribute('viewBox', box) | |
var boxDimensions = box.split(/\s+|,/) | |
img.setAttribute('width', boxDimensions[2]) | |
img.setAttribute('height', boxDimensions[3]) | |
replaceTargetWith(array[0],img.outerHTML) | |
} | |
}); | |
}; | |
xhr.onload(); | |
}; | |
xhr.send(); | |
} | |
xhr.s.push([svg, use, url_hash]); | |
if (xhr.responseText) xhr.onload(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment