-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathSVG2Bitmap.min.js
More file actions
1 lines (1 loc) · 11.2 KB
/
SVG2Bitmap.min.js
File metadata and controls
1 lines (1 loc) · 11.2 KB
1
function SVG2Bitmap(e,t,n){"use strict";if(n||(n={}),(!n.scale||n.scale<0)&&(n.scale=1),e&&e.nodeName){var r;if("OBJECT"===e.nodeName||"IFRAME"===e.nodeName){if(!e.contentDocument||"complete"===e.contentDocument.readyState&&!e.contentDocument.documentElement)return void console.error("Unable to access the svg node : make sure it comes from the same domain or that the container has finished loading");if("complete"!==e.contentDocument.readyState)return void e.addEventListener("load",d);r=e,e=e.contentDocument.documentElement}else if("EMBED"===e.nodeName&&e.getSVGDocument&&(r=e,!(e=e.getSVGDocument())))return r.addEventListener("load",d),r.onerror=function(){console.error("Unable to access the svg node : make sure it comes from the same domain or that the container has finished loading")},void(r.src=r.src);if("svg"!==e.nodeName){var a=e.querySelector("svg");if(!a){var o='[src*=".svg"]',i=e.querySelector("iframe"+o+", embed"+o)||e.querySelector('object[data*=".svg"]');return i?void SVG2Bitmap(i,t,n):void console.error("unable to access the svg node, make sure it has been appended to the document")}e=a}var l,s="http://www.w3.org/1999/xlink",c="http://www.w3.org/2000/svg",h=e.cloneNode(!0),u=function(){var e=document.createElement("canvas"),t=e.getContext("2d");e.width=e.height=1;var n=document.implementation.createHTMLDocument("test"),r=document.createElement("base");n.head.appendChild(r);var a=document.createElement("a");return n.body.appendChild(a),{isTainted:function(n){var r=!1;t.drawImage(n,0,0);try{e.toDataURL()}catch(n){r=!0,e=e.cloneNode(!0),t=e.getContext("2d")}return r},URL:function(e,t){return r.href=t,a.href=e,a}}}();!function(){var t,n=[],r=[],a=e.ownerDocument.styleSheets;for(t=0;t<a.length;t++)r.push(a[t]);r.length&&(m(),e.matches=e.matches||e.webkitMatchesSelector||e.mozMatchesSelector||e.msMatchesSelector||e.oMatchesSelector);for(t=0;t<r.length;t++){var o,i=r[t];try{o=i.cssRules}catch(e){continue}for(var d=document.createElement("style"),f=o&&o.length,g=0;g<f;g++){var p=o[g].selectorText;if(p&&(e.matches&&e.matches(p)||e.querySelector(p))){for(var w=o[g].cssText,b=new RegExp(/url\((.*?)\)/g),E=[];null!==(E=b.exec(w));){var y=E[1].replace(/\"/g,""),S=i.href||location.href;n.push([y,S]);var x=u.URL(y,S),C=S===location.href&&y.indexOf(".svg")<0?x.hash:x.href.substring(x.href.lastIndexOf("/")+1),N="#"+C.replace(/\//g,"_").replace(/\./g,"_").replace("#","_");w=w.replace(y,N)}d.innerHTML+=w+"\n"}}d.innerHTML&&l.appendChild(d)}var A=h.style;A.border=A.padding=A.margin=0,A.transform="initial",function(t){var n,r=0,a=0,o=[{href:location.href.replace(location.hash,"").replace(/#/g,""),pathname:location.pathname,filename:"",innerElements:[],parsedElements:[],doc:e.ownerDocument,base:location.href.replace(location.hash,"").replace(/#/g,"")}],i=function(){var e=document.createElementNS(c,"use");e.setAttributeNS(s,"href","#__#"),h.appendChild(e);var t=!!h.querySelector('[*|href*="#"]');return h.removeChild(e),t}(),d=function(e,t){var r,a,o,l,c,h=[],u=function(e,n){var r,a={};if(a.element=e,a.type=n,a.attributes=[],a.requestedElements=[],a.parentDoc=t,"xl"===n){if(!(r=e.attributes["xlink:href"])){var o=e.attributes.href;if(!(o&&o.namespaceURI&&o.namespaceURI.indexOf("xlink")>-1))return!1;r=o}a.attributes.push(r),a.requestedElements.push(r.value)}else{r=e.attributes;for(var i=0;i<r.length;i++)for(var l=new RegExp(/url\((.*?)\)/g),s=[];null!==(s=l.exec(r[i].value));)a.attributes.push(r[i]),a.requestedElements.push(s[1].replace(/"/g,""))}return a},d=(r=e,i?r.querySelectorAll('[*|href*="#"]'):function(){var e=[],t=r.querySelectorAll("*");for(n=0;n<t.length;n++){var a=t[n].getAttributeNS(s,"href");a&&a.indexOf("#")>-1&&e.push(t[n])}return e}()),m=(a=e,o="[*|"+["style","clip-path","src","cursor","fill","filter","marker","marker-start","marker-mid","marker-end","mask","stroke"].join('*="url"], *[*|')+'*="url"]',a.querySelectorAll(o));for(l=0;l<d.length;l++)(c=u(d[l],"xl"))&&(h.push(c),c=null);for(l=0;l<m.length;l++)(c=u(m[l],"url"))&&(h.push(c),c=null);var f=e.attributes;for(l=0;l<f.length;l++){var g=f[l];if("xlink:href"===g.name)h.push(new u(e,"xl"));else{var v=g.value.match(/url\((.*)\)/);v&&v.length>1&&h.push(new u(e,"url"))}}return h},f=function(e,t){for(var n=e.querySelectorAll("image"),r=0;r<n.length;r++){var a=n[r].getAttributeNS(s,"href"),o=u.URL(a,t).href;a!==o&&n[r].setAttributeNS(s,"href",o)}},g=function(){var e;for(e=0;e<o.length;e++){var t=o[e];if(t.doc){var n,i=t.innerElements;if(i.length!==t.parsedElements.length)for(n=0;n<i.length;n++){var s=t.doc.getElementById(i[n]);if(s){var c=s.cloneNode(!0);c.id=t.filename+"_"+i[n],f(c,t.base),l.appendChild(c),w(d(c,t)),t.parsedElements.push(i[n]),r--}else console.warn("Couldn't find this element",i[n]),r--}}}a||r||v()},p=function(e,t){for(var n=u.URL(e,t.base),i=n.href.substring(n.href.lastIndexOf("/")+1).replace(n.hash,""),l=i.replace(/\./g,"_"),s=n.hash.replace("#",""),c=n.href.replace(n.hash,""),d=l+"_"+s,m=0;m<o.length;m++){var f=o[m];if(f.href===c){if(0===m){if(h.getElementById(s))return s;d="_"+s}return f.innerElements.indexOf(s)<0?(null!==f.doc?r++:console.warn("this element is also lost ",s),f.innerElements.push(s),d):d}}r++,a++;var v,p,w,b={href:c,filename:l,innerElements:[s],parsedElements:[]};return o.push(b),p=(v=b).href,(w=new XMLHttpRequest).onload=function(){if(200===this.status){var e=this.responseText||this.response;if(!e)return;try{v.doc=(new DOMParser).parseFromString(e,"text/html")}catch(t){v.doc=document.implementation.createHTMLDocument(v.filename),v.doc.body.innerHTML=e}v.base=p}else v.doc=null,r-=v.innerElements.length,console.warn("could not load this external document :",p,"\nThose elements are lost : ",v.innerElements.join(" , "));--a||g()},w.onerror=function(e){v.doc=null,r-=v.innerElements.length,console.warn("could not load this external document",p),console.warn("Those elements are lost : ",v.innerElements.join(" , ")),--a||g()},w.open("GET",p),w.send(),d},w=function(e){var t,n;for(e.length&&!l&&m(),t=0;t<e.length;t++){var r=e[t];for(n=0;n<r.requestedElements.length;n++){var a=r.requestedElements[n],o="#"+p(a,r.parentDoc),i=r.attributes[n],s=i.value.replace(a,o),c=i.name.toUpperCase()===i.name?i.name.toLowerCase():i.name;r.element.setAttribute(c,s)}}};for(n=0;n<t.length;n++)p(t[n][0],{base:t[n][1]});w(d(h,o[0])),a||(r?g():v())}(n)}()}else console.error("Wrong arguments : should be \n SVG2Bitmap(SVGElement, function([canvasElement],[dataURL]) || IMGElement || CanvasElement [, {parameters})");function d(){this.removeEventListener("load",d),SVG2Bitmap(this,t,n)}function m(){(l=h.querySelector("defs")||document.createElementNS(c,"defs")).parentNode||h.insertBefore(l,h.firstElementChild)}function f(){var a,o=r?r.getBoundingClientRect():e.getBoundingClientRect();function i(e){for(var t=Array.prototype.slice.call(e.attributes),n=0;n<t.length;n++){var r=t[n].name;r.indexOf(":")>-1&&r.indexOf("xlink")<0&&e.removeAttribute(r)}}if(1!==e.width.baseVal.unitType&&h.setAttribute("width",o.width),1!==e.height.baseVal.unitType&&h.setAttribute("height",o.height),"undefined"!=typeof ActiveXObject){i(h);for(var l=h.querySelectorAll("*"),s=0;s<l.length;s++)i(l[s])}h.removeAttribute("style"),a=(new XMLSerializer).serializeToString(h);var c="data:image/svg+xml; charset=utf8, "+encodeURIComponent(a),d=new Image;d.onload=function a(){var i=t&&"CANVAS"===t.nodeName?t:document.createElement("canvas");if(i.originalSVG=r||e,i.width=o.width*n.scale,i.height=o.height*n.scale,i.width&&i.height){var l=i.getContext("2d");n.backgroundColor&&(l.fillStyle=n.backgroundColor,l.fillRect(0,0,i.width,i.height));var s=n.scale,c=r?e.getBoundingClientRect():{top:0,left:0};try{l.drawImage(this,c.left,c.top,this.width*s||i.width,this.height*s||i.height)}catch(e){setTimeout(a.bind(this),200)}if(t||(t=function(t){var n=r||e;n.parentNode.replaceChild(t,n)}),u.isTainted(i))return console.warn("Your browser has tainted the canvas."),void("IMG"===t.nodeName?t.parentNode.replaceChild(i,t):(i.setAttribute("style",g(i)),t!==i&&t.appendChild?t.appendChild(i):"function"==typeof t&&t(i,null)));"IMG"===t.nodeName?(t.setAttribute("style",g(t)),t.src=i.toDataURL(n.type,n.quality)):(i.setAttribute("style",g(i)),t!==i&&t.appendChild?t.appendChild(i):"function"==typeof t&&t(i,i.toDataURL(n.type,n.quality)))}else console.error("The document is not visible and can not be rendered")},d.onerror=function(e){console.error("Couldn't export svg, please check that the svgElement passed is a valid svg document.")},d.src=c}function g(t){var n=t.cloneNode(!0);e.parentNode.documentElement?e.parentNode.documentElement.appendChild(n):e.parentNode.insertBefore(n,e);for(var a=getComputedStyle(n),o=getComputedStyle(r||e),i="",l=0;l<o.length;l++)"width"!==o[l]&&"height"!==o[l]&&o[o[l]]!==a[o[l]]&&(i+=o[l]+":"+o[o[l]]+";");return n.parentNode.removeChild(n),i}function v(){var t,r=h.querySelectorAll("image"),a=r.length,o=0;if(0!==a){var i=[],l=e.querySelectorAll("image");for(t=0;t<r.length;t++)if(l[t]&&l[t].isEqualNode(r[t]))i.push(l[t]);else{for(var c=null,d=0;d<l.length;d++)if(l[d].isEqualNode(r[t])){c=l[d];break}i.push(c)}var m=document.createElement("canvas"),g=m.getContext("2d");for(t=0;t<r.length;t++){var v=r[t].getAttributeNS(s,"href");if(v&&v.indexOf("data:image")<0)v.indexOf(".svg")>0?b(v,r[t]):w(r[t],i[t]);else if(++o===a)return void f()}}else f();function p(e){var t=new Image;t.onload=function(){++o===a&&f()},t.src=e}function w(e,t){var r=new Image,i=function(){console.warn("failed to load an image at : ",r.src),n.keepImageHolder||e.parentNode.removeChild(e),--a===o&&f()};n.noCORS||(r.crossOrigin="Anonymous"),r.onload=function(){var r,a;if(t&&(r=e.getAttribute("preserveAspectRatio"),a=t.getBoundingClientRect()),t&&a&&(a.width*n.scale<this.width||a.height*n.scale<this.height)){m.width=a.width*n.scale,m.height=a.height*n.scale;var o=function(e,t,n){var r=e.width,a=e.height,o=t.width,i=t.height;function l(e){var t=a/r,n=i/o,l=n>t?o:i/t,h=n>t?o*t:i;function u(e,t,n){var r=Math.max(t,n),a=Math.min(t,n);switch(e){case"Min":return 0;case"Mid":return(r-a)/2;case"Max":return r-a;default:return"invalid"}}var d=[s,0,0,r,a,u(e[0],l,o),u(e[1],h,i),l,h];return"invalid"===d[5]||"invalid"===d[6]?c:d}var s="IMG"===e.nodeName||"VIDEO"===e.nodeName||"CANVAS"===e.nodeName?e:null,c=l(["Mid","Mid"]);{if(!n)return c;var h=n.trim().split(" "),u=h[0].replace("x","").split("Y");switch(h[h.length-1]){case"meet":return l(u);case"slice":return function(e){var t,n;function l(){t=o,n=a*o/r}function h(){t=r*i/a,n=i}o>i?(l(),i>n&&h()):o===i?r>a?h():l():(h(),o>t&&l());function u(e,t,n,r){switch(e){case"Min":return 0;case"Mid":return(t-n)/2*r/t;case"Max":return(t-n)*r/t;default:return"invalid"}}var d=u(e[0],t,o,r),m=u(e[1],n,i,a),f=[s,d,m,r-d,a-m,0,0,t-d*(t/r),n-m*(n/a)];if("invalid"===f[1]||"invalid"===f[2])return c;return f}(u);default:return c}}}(this,m,r);g.drawImage.apply(g,o)}else m.width=this.width,m.height=this.height,g.drawImage(this,0,0);if(u.isTainted(m))i();else{var l=m.toDataURL();e.setAttributeNS(s,"href",l),p(l)}},r.onerror=function(){var e=this.src;this.onerror=i,this.removeAttribute("crossorigin"),this.src="",this.src=e},r.src=e.getAttributeNS(s,"href")}function b(e,t){var n=new XMLHttpRequest;n.onload=function(){if(200===this.status){var e=this.responseText||this.response,n="data:image/svg+xml; charset=utf8, "+encodeURIComponent("<svg"+e.split("<svg")[1]);t.setAttributeNS(s,"href",n),p(n)}else w(t)},n.onerror=function(){w(t)};try{n.open("GET",e)}catch(e){return void w(t)}n.send()}}}