【问题标题】:How to embed SVG with Path into Html taken from a src?如何将带有路径的 SVG 嵌入到从 src 获取的 Html 中?
【发布时间】:2021-11-29 01:13:19
【问题描述】:

我有一个 svg 上传到我的网站,我想将它嵌入到我的 html 中,以便它可以具有 svg 和路径的结构:

<svg>
    <path id="svgPath"/>
</svg>

我设法用图像做到了

<svg width="1920" height"720">
  <image id="imgId" xlink:href="srclink" width="1920" height="720" />
</svg>

当我查询该图像时,我没有与 path 元素相同的方法。例如,我没有.getTotalLength()

const path = document.querySelector("#pathId");
path.getTotalLength(); // will work

const img = document.querySelector("#imgId");
img.getTotallength(); // does not work

如果从srclink 加载它时有办法做到这一点,我也可以使用 Javascript 插入它。

need 能够访问该路径,因为我的其余代码都依赖于此。

【问题讨论】:

    标签: javascript html svg


    【解决方案1】:

    如果是外部的*.svg文件,一个原生的Web Component&lt;load-file&gt;可以获取它并注入到DOM中;在 shadowDOM 中或替换 &lt;load-file&gt; 元素,从而成为 DOM 的一部分,您可以使用 CSS 访问和设置样式。

    customElements.define("load-file", class extends HTMLElement {
    
      // declare default connectedCallback as sync so await can be used
      async connectedCallback(
        // call connectedCallback with parameter to *replace* SVG (of <load-file> persists)
        src = this.getAttribute("src"),
        // attach a shadowRoot if none exists (prevents displaying error when moving Nodes)
        shadowRoot = this.shadowRoot || this.attachShadow({mode:"open"})
      ) {
          // load SVG file from src="" async, parse to text, add to shadowRoot.innerHTML
        shadowRoot.innerHTML = await (await fetch(src)).text()
    
        // append optional <tag [shadowRoot]> Elements from inside <load-svg> after parsed <svg>
        shadowRoot.append(...this.querySelectorAll("[shadowRoot]"))
    
        // if "replaceWith" attribute 
        // then replace <load-svg> with loaded content <load-svg>
        // childNodes instead of children to include #textNodes also
        this.hasAttribute("replaceWith") && this.replaceWith(...shadowRoot.childNodes)
      }
    })
    

    Dev.To 中的完整解释发帖:〈load-file〉Web Component, add external content to the DOM

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-13
      • 2017-08-19
      • 2017-08-13
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      • 2021-06-27
      • 1970-01-01
      相关资源
      最近更新 更多