How to modify function to accept 2 SVG to convert to Base64?

I have this Js code which allows me to pass the ID of an SVG as a parameter and convert it to BASE64 png

    (function() {
  const out$ = typeof exports != 'undefined' && exports || typeof define != 'undefined' && {} || this || window;
  if (typeof define !== 'undefined') define('save-svg-as-png', (), () => out$);
  out$.default = out$;

  const xmlNs = 'http://www.w3.org/2000/xmlns/';
  const xhtmlNs = 'http://www.w3.org/1999/xhtml';
  const svgNs = 'http://www.w3.org/2000/svg';
  const doctype = ')>';
  const urlRegex = /url(("')?(.+?)("')?)/;
  const fontFormats = {
    woff2: 'font/woff2',
    woff: 'font/woff',
    otf: 'application/x-font-opentype',
    ttf: 'application/x-font-ttf',
    eot: 'application/vnd.ms-fontobject',
    sfnt: 'application/font-sfnt',
    svg: 'image/svg+xml'
  };

  const isElement = obj => obj instanceof HTMLElement || obj instanceof SVGElement;
  const requireDomNode = el => {
    if (!isElement(el)) throw new Error(`an HTMLElement or SVGElement is required; got ${el}`);
  };
  const requireDomNodePromise = el =>
    new Promise((resolve, reject) => {
      if (isElement(el)) resolve(el)
      else reject(new Error(`an HTMLElement or SVGElement is required; got ${el}`));
    })
  const isExternal = url => url && url.lastIndexOf('http',0) === 0 && url.lastIndexOf(window.location.host) === -1;

  const getFontMimeTypeFromUrl = fontUrl => {
    const formats = Object.keys(fontFormats)
      .filter(extension => fontUrl.indexOf(`.${extension}`) > 0)
      .map(extension => fontFormats(extension));
    if (formats) return formats(0);
    console.error(`Unknown font format for ${fontUrl}. Fonts may not be working correctly.`);
    return 'application/octet-stream';
  };

  const arrayBufferToBase64 = buffer => {
    let binary = '';
    const bytes = new Uint8Array(buffer);
    for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes(i));
    return window.btoa(binary);
  }

  const getDimension = (el, clone, dim) => {
    const v =
      (el.viewBox && el.viewBox.baseVal && el.viewBox.baseVal(dim)) ||
      (clone.getAttribute(dim) !== null && !clone.getAttribute(dim).match(/%$/) && parseInt(clone.getAttribute(dim))) ||
      el.getBoundingClientRect()(dim) ||
      parseInt(clone.style(dim)) ||
      parseInt(window.getComputedStyle(el).getPropertyValue(dim));
    return typeof v === 'undefined' || v === null || isNaN(parseFloat(v)) ? 0 : v;
  };

  const getDimensions = (el, clone, width, height) => {
    if (el.tagName === 'svg') return {
      width: width || getDimension(el, clone, 'width'),
      height: height || getDimension(el, clone, 'height')
    };
    else if (el.getBBox) {
      const {x, y, width, height} = el.getBBox();
      return {
        width: x + width,
        height: y + height
      };
    }
  };

  const reEncode = data =>
    decodeURIComponent(
      encodeURIComponent(data)
        .replace(/%((0-9A-F){2})/g, (match, p1) => {
          const c = String.fromCharCode(`0x${p1}`);
          return c === '%' ? '%25' : c;
        })
    );

  const uriToBlob = uri => {
    const byteString = window.atob(uri.split(',')(1));
    const mimeString = uri.split(',')(0).split(':')(1).split(';')(0)
    const buffer = new ArrayBuffer(byteString.length);
    const intArray = new Uint8Array(buffer);
    for (let i = 0; i < byteString.length; i++) {
      intArray(i) = byteString.charCodeAt(i);
    }
    return new Blob((buffer), {type: mimeString});
  };

  const query = (el, selector) => {
    if (!selector) return;
    try {
      return el.querySelector(selector) || el.parentNode && el.parentNode.querySelector(selector);
    } catch(err) {
      console.warn(`Invalid CSS selector "${selector}"`, err);
    }
  };

  const detectCssFont = (rule, href) => {
    // Match CSS font-face rules to external links.
    // @font-face {
    //   src: local('Abel'), url(https://fonts.gstatic.com/s/abel/v6/UzN-iejR1VoXU2Oc-7LsbvesZW2xOQ-xsNqO47m55DA.woff2);
    // }
    const match = rule.cssText.match(urlRegex);
    const url = (match && match(1)) || '';
    if (!url || url.match(/^data:/) || url === 'about:blank') return;
    const fullUrl =
      url.startsWith('../') ? `${href}/../${url}`
      : url.startsWith('./') ? `${href}/.${url}`
      : url;
    return {
      text: rule.cssText,
      format: getFontMimeTypeFromUrl(fullUrl),
      url: fullUrl
    };
  };

  const inlineImages = el => Promise.all(
    Array.from(el.querySelectorAll('image')).map(image => {
      let href = image.getAttributeNS('http://www.w3.org/1999/xlink', 'href') || image.getAttribute('href');
      if (!href) return Promise.resolve(null);
      if (isExternal(href)) {
        href += (href.indexOf('?') === -1 ? '?' : '&') + 't=' + new Date().valueOf();
      }
      return new Promise((resolve, reject) => {
        const canvas = document.createElement('canvas');
        const img = new Image();
        img.crossOrigin = 'anonymous';
        img.src = href;
        img.onerror = () => reject(new Error(`Could not load ${href}`));
        img.onload = () => {
          canvas.width = img.width;
          canvas.height = img.height;
          canvas.getContext('2d').drawImage(img, 0, 0);
          image.setAttributeNS('http://www.w3.org/1999/xlink', 'href', canvas.toDataURL('image/png'));
          resolve(true);
        };
      });
    })
  );

  const cachedFonts = {};
  const inlineFonts = fonts => Promise.all(
    fonts.map(font =>
      new Promise((resolve, reject) => {
        if (cachedFonts(font.url)) return resolve(cachedFonts(font.url));

        const req = new XMLHttpRequest();
        req.addEventListener('load', () => {
          // TODO: it may also be worth it to wait until fonts are fully loaded before
          // attempting to rasterize them. (e.g. use https://developer.mozilla.org/en-US/docs/Web/API/FontFaceSet)
          const fontInBase64 = arrayBufferToBase64(req.response);
          const fontUri = font.text.replace(urlRegex, `url("data:${font.format};base64,${fontInBase64}")`)+'n';
          cachedFonts(font.url) = fontUri;
          resolve(fontUri);
        });
        req.addEventListener('error', e => {
          console.warn(`Failed to load font from: ${font.url}`, e);
          cachedFonts(font.url) = null;
          resolve(null);
        });
        req.addEventListener('abort', e => {
          console.warn(`Aborted loading font from: ${font.url}`, e);
          resolve(null);
        });
        req.open('GET', font.url);
        req.responseType = 'arraybuffer';
        req.send();
      })
    )
  ).then(fontCss => fontCss.filter(x => x).join(''));

  let cachedRules = null;
  const styleSheetRules = () => {
    if (cachedRules) return cachedRules;
    return cachedRules = Array.from(document.styleSheets).map(sheet => {
      try {
        return {rules: sheet.cssRules, href: sheet.href};
      } catch (e) {
        console.warn(`Stylesheet could not be loaded: ${sheet.href}`, e);
        return {};
      }
    });
  };

  const inlineCss = (el, options) => {
    const {
      selectorRemap,
      modifyStyle,
      modifyCss,
      fonts,
      excludeUnusedCss
    } = options || {};
    const generateCss = modifyCss || ((selector, properties) => {
      const sel = selectorRemap ? selectorRemap(selector) : selector;
      const props = modifyStyle ? modifyStyle(properties) : properties;
      return `${sel}{${props}}n`;
    });
    const css = ();
    const detectFonts = typeof fonts === 'undefined';
    const fontList = fonts || ();
    styleSheetRules().forEach(({rules, href}) => {
      if (!rules) return;
      Array.from(rules).forEach(rule => {
        if (typeof rule.style != 'undefined') {
          if (query(el, rule.selectorText)) css.push(generateCss(rule.selectorText, rule.style.cssText));
          else if (detectFonts && rule.cssText.match(/^@font-face/)) {
            const font = detectCssFont(rule, href);
            if (font) fontList.push(font);
          } else if (!excludeUnusedCss) {
            css.push(rule.cssText);
          }
        }
      });
    });

    return inlineFonts(fontList).then(fontCss => css.join('n') + fontCss);
  };

  const downloadOptions = () => {
    if (!navigator.msSaveOrOpenBlob && !('download' in document.createElement('a'))) {
      return {popup: window.open()};
    }
  };

  out$.prepareSvg = (el, options, done) => {
    requireDomNode(el);
    const {
      left = 0,
      top = 0,
      width: w,
      height: h,
      scale = 1,
      responsive = false,
      excludeCss = false,
    } = options || {};

    return inlineImages(el).then(() => {
      let clone = el.cloneNode(true);
      clone.style.backgroundColor = (options || {}).backgroundColor || el.style.backgroundColor;
      const {width, height} = getDimensions(el, clone, w, h);

      if (el.tagName !== 'svg') {
        if (el.getBBox) {
          if (clone.getAttribute('transform') != null) {
            clone.setAttribute('transform', clone.getAttribute('transform').replace(/translate(.*?)/, ''));
          }
          const svg = document.createElementNS('http://www.w3.org/2000/svg','svg');
          svg.appendChild(clone);
          clone = svg;
        } else {
          console.error('Attempted to render non-SVG element', el);
          return;
        }
      }

      clone.setAttribute('version', '1.1');
      clone.setAttribute('viewBox', (left, top, width, height).join(' '));
      if (!clone.getAttribute('xmlns')) clone.setAttributeNS(xmlNs, 'xmlns', svgNs);
      if (!clone.getAttribute('xmlns:xlink')) clone.setAttributeNS(xmlNs, 'xmlns:xlink', 'http://www.w3.org/1999/xlink');

      if (responsive) {
        clone.removeAttribute('width');
        clone.removeAttribute('height');
        clone.setAttribute('preserveAspectRatio', 'xMinYMin meet');
      } else {
        clone.setAttribute('width', width * scale);
        clone.setAttribute('height', height * scale);
      }

      Array.from(clone.querySelectorAll('foreignObject > *')).forEach(foreignObject => {
        foreignObject.setAttributeNS(xmlNs, 'xmlns', foreignObject.tagName === 'svg' ? svgNs : xhtmlNs);
      });

      if (excludeCss) {
        const outer = document.createElement('div');
        outer.appendChild(clone);
        const src = outer.innerHTML;
        if (typeof done === 'function') done(src, width, height);
        else return {src, width, height};
      } else {
        return inlineCss(el, options).then(css => {
          const style = document.createElement('style');
          style.setAttribute('type', 'text/css');
          style.innerHTML = ``;

          const defs = document.createElement('defs');
          defs.appendChild(style);
          clone.insertBefore(defs, clone.firstChild);

          const outer = document.createElement('div');
          outer.appendChild(clone);
          const src = outer.innerHTML.replace(/NSd+:href/gi, 'xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href');

          if (typeof done === 'function') done(src, width, height);
          else return {src, width, height};
        });
      }
    });
  };

  out$.svgAsDataUri = (el, options, done) => {
    requireDomNode(el);
    return out$.prepareSvg(el, options)
      .then(({src, width, height}) => {
          const svgXml = `data:image/svg+xml;base64,${window.btoa(reEncode(doctype+src))}`;
          if (typeof done === 'function') {
              done(svgXml, width, height);
          }
          return svgXml;
      });
  };

  out$.svgAsPngUri = (el, options, done) => {
    requireDomNode(el);
    const {
      encoderType = 'image/png',
      encoderOptions = 0.8,
      canvg
    } = options || {};

    const convertToPng = ({src, width, height}) => {
      const canvas = document.createElement('canvas');
      const context = canvas.getContext('2d');
      const pixelRatio = window.devicePixelRatio || 1;

      canvas.width = width * pixelRatio;
      canvas.height = height * pixelRatio;
      canvas.style.width = `${canvas.width}px`;
      canvas.style.height = `${canvas.height}px`;
      context.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);

      if (canvg) canvg(canvas, src);
      else context.drawImage(src, 0, 0);

      let png;
      try {
        png = canvas.toDataURL(encoderType, encoderOptions);
      } catch (e) {
        if ((typeof SecurityError !== 'undefined' && e instanceof SecurityError) || e.name === 'SecurityError') {
          console.error('Rendered SVG images cannot be downloaded in this browser.');
          return;
        } else throw e;
      }
      if (typeof done === 'function') done(png, canvas.width, canvas.height);
      return Promise.resolve(png);
    }

    if (canvg) return out$.prepareSvg(el, options).then(convertToPng);
    else return out$.svgAsDataUri(el, options).then(uri => {
      return new Promise((resolve, reject) => {
        const image = new Image();
        image.onload = () => resolve(convertToPng({
          src: image,
          width: image.width,
          height: image.height
        }));
        image.onerror = () => {
          reject(`There was an error loading the data URI as an image on the following SVGn${window.atob(uri.slice(26))}Open the following link to see browser's diagnosisn${uri}`);
        }
        image.src = uri;
      })
    });
  };

  out$.download = (name, uri, options) => {
    console.log(name+' | '+uri+' | '+options)

    if (navigator.msSaveOrOpenBlob) navigator.msSaveOrOpenBlob(uriToBlob(uri), name);
    else {
      const saveLink = document.createElement('a');
      // if ('download' in saveLink) {
      //   saveLink.download = name;
      //   saveLink.style.display = 'none';
      //   document.body.appendChild(saveLink);
      //   console.log(saveLink)
      //   try {
      //     const blob = uriToBlob(uri);
      //     const url = URL.createObjectURL(blob);
      //     saveLink.href = url;
      //     saveLink.onclick = () => requestAnimationFrame(() => URL.revokeObjectURL(url));
      //   } catch (e) {
      //     console.error(e);
      //     console.warn('Error while getting object URL. Falling back to string URL.');
      //     saveLink.href = uri;
      //   }
      //   saveLink.click();
      //   document.body.removeChild(saveLink);
      // } else if (options && options.popup) {
      //   options.popup.document.title = name;
      //   options.popup.location.replace(uri);
      // }
    }
  };

  out$.saveSvg = (el, name, options) => {
    const downloadOpts = downloadOptions(); // don't inline, can't be async
    return requireDomNodePromise(el)
      .then(el => out$.svgAsDataUri(el, options || {}))
      .then(uri => out$.download(name, uri, downloadOpts));
  };

  out$.saveSvgAsPng = (el, name, options) => {
    const downloadOpts = downloadOptions(); // don't inline, can't be async
    return requireDomNodePromise(el)
      .then(el => out$.svgAsPngUri(el, options || {}))
      .then(uri => out$.download(name, uri, downloadOpts));
  };
})();

saveSvgAsPng (document.getElementById ("HumanHuman"), "download-name.png");

The code I have modified so that it only gives me an alert of the Base64 code, since at first the function what it did was to download the image as such; and I just want Base64 png

And even there it works perfectly the thing is that I need to pass not 1 SVG ID but I need to pass 2 SVG ID

Something similar to this

saveSvgAsPng(document.getElementById("CuerpoHumano1"),document.getElementById("CuerpoHumano2"), "nombre-de-descarga.png");

And to be able to obtain the Base64 code with that format, just thank you in advance

php – How to add an SVG icon over the product tab title

I used the following code to create custom product tabs (woocommerce), and now I was wondering if I can add an SVG icon over the tab title.

My code for a custom product tab:

add_filter( 'woocommerce_product_tabs', 'misha_custom_tab' );

function misha_custom_tab( $tabs ) {

    $tabs('misha_custom_tab') = array(
        'title'    => 'MyTabTitle',
        'callback' => 'misha_custom_tab_content', // the function name, which is on line 15
        'priority' => 50,
    );

    return $tabs;

}

function misha_custom_tab_content( $slug, $tab ) {

    echo '

' . $tab('title') . '

Tab Content. You can display something in PHP here as well.

'; }

Image examples:

Before:
before

After:
enter the image description here

How can I add an SVG icon over the title of the product tab?

Nginx Proxy svg broken

Hi,

We have configured Nginx as Edge node. The website works fine from the edge (caching and proxy requests to the source as needed). However, prox … | Read the rest of https://www.webhostingtalk.com/showthread.php?t=1802218&goto=newpost

Is it possible to make an infinitely self-similar fractal in SVG?

When I say self-similar fractal, I don't mean a fractal that is finitely detailed I mean a infinitely Detailed SVG (that is, when you zoom in, you don't find any limits for the fractal). Is this possible? For example, could you build an infinitely detailed version of the Serpinski triangle in SVG?

Add SVG online to Gutenberg core / quote block

I want to extend the Gutenberg quote block / core using an inline SVG (quote symbol) to the html and add a color panel so the color can be changed.

Any clues on how to do this?

Neque porro quisquam est qui dolorem ipsum quia dolor sit amet adipisci velit

Lorem Ipsum

javascript – Error in button svg animation

I am creating an animation on a button in svg, I am creating with .is-loading and .is-success, but pressing the button does not make the animation and I cannot identify the problem that is occurring.

here is the code

var resultado = document.getElementById("campo_enviar");

resultado.addEventListener('click', function btn() {
  resultado.classList.add('is-loading');

  setTimeout(() => {
    resultado.classList.add('is-success');
    resultado.classList.remove('is-loading');
    resultado.removeEventListener('click', btn);
  }, 4000);
});
.btn_enviar {
  position: absolute;
  top: 5px;
  right: 110px;
  background: none;
  color: #000;
  border: 1px solid #45981B;
  border-radius: 40px;
  box-shadow: 0 0 0 0 rgba(69, 152, 27, 0.5);
  cursor: pointer;
  height: 45px;
  width: 10px;
  outline: none;
  padding: 15px 70px;
  transition: background, padding 500ms ease-in-out;
}

span {
  font-size: 15px;
  position: absolute;
  top: 12px;
  left: 36px;
}

.btn_enviar.is-loading {
  animation: pulse 1.5s infinite;
  padding: 15px 7px;
}

.btn_enviar.is-success {
  background: #45981B;
  padding: 15px 7px;
}

svg {
  width: 0;
  height: 0;
}

.is-success svg {
  height: 30px;
  width: 30px;
}

.check {
  stroke-dasharray: 130px 130px;
  stroke-dashoffset: 130px;
  transition: stroke-dashoffset 500ms ease-in-out;
}

.is-loading span,
.is-success span {
  display: none;
}

.is-success .check {
  stroke-dashoffset: 0px;
}

@keyframes pulse {
  0% {
    transform: scale(.9);
  }
  70% {
    transform: scale(1);
    box-shadow: 0 0 0 50px rgba(69, 152, 27, 0);
  }
  100% {
    transform: scale(.9);
    box-shadow: 0 0 0 0 rgba(69, 152, 27, 0);
  }
}

, where is the button and svg. follow down.

Topic: Twenty-nine // How to exclude cookie control triangle and svg star from being replaced by css theme "svg {fill: currentColor;}"

I implemented the civic control of cookies on my website https://ingereck.net. Everything works fine except the ccc icon (triangle and star) not shown (bottom right of my page).

Theme css

svg {
padding: currentColor;
}

You are canceling it.

I tried the solution

svg: not (#triangle) {
padding: currentColor;
}

but it doesn't work or the selector is not correct.

Any idea how to solve this?

macbook pro: find files of certain extensions like * .svg, *. jpg, *. sketch and move them to a specific folder structure. Using Mac Automator

I am new to automated on mac. I'm just playing around to see if I can get the expected result for this problem I'm having:

"I am a designer and I have to download lots of files from the Internet to get references and therefore my download folder gets messy and I wanted to organize it in a specific way. Just like I have files like jpg, svg, eps, sketch, etc. I have the following folder structure created, and I want some kind of automation to move the respective extension files to the respective folder in the folder structure as they are added to the download folder the first time. I was looking for options and discovered that the automator can be used for this. "

Folder structure as follows

  • Animations
    • Key notes
    • Beginning
    • Design Files
    • Affinity files
    • Sketch files
    • Desk
    • Documents
    • Sources
    • Images
    • Icons
    • Plot
    • Vector
    • Other files
    • Softwares
    • Videos

I tried to create folder actions in the automater for this. I added the following conditions

  • Find search engine articles
    • Entry = Download folder Search = Equipment condition = all / any depending on my need of the respective folder structure
      criteria = IS file extension jpg / png / svg / eps / etc as per my need.
  • Move Finder Item
    • To = Specific folder based on the respective extension.

I tried to create a single script with all the conditions like if-else / switch like:
If the extension is .jpg, move it to Image> Raster> Jpg folder
If the extension is .svg, move it to Image> Vector> SVG folder
etcetera etcetera,..

Single file with data:
enter the image description here

But it was not working properly. I was moving files randomly to random folders.

Then I created separate rules for separate files but they still behave the same way. I am not sure why.

Could someone help me on this?

How to prevent Google Drive from trying to process .svg files as images

I have some .svg files created in Inkscape.

I don't want or need to be converted / compressed for storage on Google Drive; just to be backed up.

How can i stop the Can't add files to Google Photos Does a message appear every time I sync?