svg-png.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /**
  2. * Minified by jsDelivr using Terser v5.15.1.
  3. * Original file: /npm/d3-svg-to-png@0.3.1/index.js
  4. *
  5. * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
  6. */
  7. function inlineStyles(e, t) {
  8. const n = window.getComputedStyle(e);
  9. for (const e of n) t.style[e] = n[e];
  10. for (let n = 0; n < e.children.length; n++) inlineStyles(e.children[n], t.children[n]);
  11. }
  12. function copyToCanvas({ source: e, target: t, scale: n, format: o, quality: l }) {
  13. let a = new XMLSerializer().serializeToString(t),
  14. i = document.createElement("canvas"),
  15. r = e.getBoundingClientRect();
  16. (i.width = r.width * n), (i.height = r.height * n), (i.style.width = r.width), (i.style.height = r.height);
  17. let c = i.getContext("2d");
  18. c.scale(n, n);
  19. let d = document.createElement("img");
  20. return (
  21. d.setAttribute("src", "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(a)))),
  22. new Promise((e) => {
  23. d.onload = () => {
  24. c.drawImage(d, 0, 0), e(i.toDataURL(`image/${"jpg" === o ? "jpeg" : o}`, l));
  25. };
  26. })
  27. );
  28. }
  29. function downloadImage({ file: e, name: t, format: n }) {
  30. let o = document.createElement("a");
  31. (o.download = `${t}.${n}`), (o.href = e), document.body.appendChild(o), o.click(), document.body.removeChild(o);
  32. }
  33. async function svgToPng(
  34. e,
  35. t,
  36. {
  37. scale: n = 1,
  38. format: o = "png",
  39. quality: l = 0.92,
  40. download: a = !0,
  41. ignore: i = null,
  42. cssinline: r = 1,
  43. background: c = null,
  44. } = {}
  45. ) {
  46. e = e instanceof Element ? e : document.querySelector(e);
  47. const d = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  48. d.innerHTML = e.innerHTML;
  49. for (const t of e.attributes) d.setAttribute(t.name, t.value);
  50. if ((1 === r && inlineStyles(e, d), c && (d.style.background = c), null != i)) {
  51. const e = d.querySelectorAll(i);
  52. [].forEach.call(e, (e) => e.parentNode.removeChild(e));
  53. }
  54. const s = await copyToCanvas({ source: e, target: d, scale: n, format: o, quality: l });
  55. return a && downloadImage({ file: s, name: t, format: o }), s;
  56. }
  57. window.svgToPng = svgToPng;
  58. //# sourceMappingURL=/sm/14eea0125d103380ac8a8d5d87aec7122e2b707361f72c63dfeb2e62361d38e4.map