xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

SVG namespace & SVG preview bug All In One

SVG namespace & SVG preview bug All In One

error

This XML file does not appear to have any style information associated with it. The document tree is shown below.

bad xml close tag

Ok

solution & svg namespace


<?xml version="1.0" encoding="UTF-8"?>
<svg width="976px" height="471px" viewBox="0 0 976 471" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
</svg>

responsive viewbox

    svgAutoConvert(svgStr) {
      const viewport = `<svg width="100%" height="100%" viewBox="0 0 1000 1000" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">`;
      // const viewport = `<svg width="100%" height="100%" viewBox="0 0 1000 1000">`;
      const xml = /<\?xml[\s\S]*\?>/i;
      let result = ``;
      result = svgStr.replace(xml,``);
      let index = result.indexOf(`>`);
      result = result.substr(index + 1);
      result = viewport + result;
      // log(`new result`, result);
      return result;
    },
    svgAutoScale(svgStr) {
      let result = ``;
      // 匹配任意字符 (\s*\S\s*)* 或 [\s\S]* ???
      const reg  = /[\s\S]*^<svg(\s*\S\s*)*>$/i;
      result = svgStr.replace(reg, `<svg width="100%" height="100%" viewBox="0 0 1000 1000" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">`);
      log(`result`, result);
      return result;
    },

auto Svg Download

const autoSvgDownload = (filename = `live-map.svg`) =>{
  const svg = document.querySelector(`svg`);
  const html = svg.parentElement.innerHTML;
  // xml namespace, support browser open preview
  const xml = `<?xml version="1.0" encoding="UTF-8"?>\n${html}`;
  console.log(`xml`, xml);
  console.log(`encodeURIComponent(xml)`, encodeURIComponent(xml));
  const element = document.createElement('a');
  element.setAttribute('href', 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(xml));
  element.setAttribute('download', filename);
  element.style.display = 'none';
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);
}

demos

https://cdn.xgqfrms.xyz/svg/namespace/poly.svg

https://cdn.xgqfrms.xyz/svg/namespace/poly-bug.svg

vscode svg preview

https://marketplace.visualstudio.com/items?itemName=cssho.vscode-svgviewer

https://marketplace.visualstudio.com/items?itemName=jock.svg&WT.mc_id=vscoderelease-medium-buhollan

https://www.freecodecamp.org/news/things-you-need-to-know-about-working-with-svg-in-vs-code-63be593444dd/

refs



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2020-02-14 13:01  xgqfrms  阅读(309)  评论(10编辑  收藏  举报