如何获取要插入到 DOM 中的 SVG 文档数据? [英] How to get SVG document data to be inserted into the DOM?

查看:40
本文介绍了如何获取要插入到 DOM 中的 SVG 文档数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码从 CDN 加载 SVG 文件:

I'm trying to load an SVG file from a CDN using this code:

SVG 文件位于 CloudFront CDN 提供的 S3 存储桶中.它的内容类型设置为image/svg+xml".据我所知,我的 S3 存储桶和 CDN 配置为允许来自任何来源的 CORS 请求.

The SVG file is in an S3 bucket served by CloudFront CDN. It's content-type is set to "image/svg+xml". To the best of my knowledge, my S3 bucket and CDN are configured to allow CORS requests from any origin.

如果我查看浏览器的网络"选项卡,HTTP GET 请求会成功并接收 SVG 数据作为响应.但是文档数据并没有插入到DOM中,所以它不显示,也不能被JavaScript访问.

If I look at the browser Network tab, the HTTP GET request succeeds and it receives the SVG data in response. However, the document data is not inserted into the DOM, so it doesn't display and cannot be accessed by JavaScript.

如何将 SVG 文档嵌入到我的网页中,使其成为 DOM 的可访问部分?

How can I embed the SVG document into my webpage so that it becomes an accessible part of the DOM?

推荐答案

只要你被允许读取 SVG,这个原生 Web Component

Provided you are allowed to read the SVG, this native Web Component <load-svg>

  • 将 SVG 读取为文本
  • 将 SVG 作为 DOM 元素添加到 shadowDOM 中
  • 移动样式元素从 lightDOMshadowDOM
    所以样式应用于当前的SVG
  • reads the SVG as text
  • adds SVG to shadowDOM as DOM element
  • moves the style element from lightDOM to shadowDOM
    So style is only applied to current SVG

<load-svg src="//graphviz.org/Gallery/directed/fsm.svg">
  <style>
    svg  { height:180px }
    text { stroke: green }
    path { stroke: red ; stroke-width:3 }
  </style>
</load-svg>

<script>
  customElements.define('load-svg', class extends HTMLElement {
    async connectedCallback() {
      let src = this.getAttribute("src");
      let svg = await (await fetch(src)).text();
      this.attachShadow({ mode: 'open' }).innerHTML = svg;
      this.shadowRoot.append(this.querySelector("style"));
    }
 });
</script>

更复杂的例子:如何使 svg 互动以收集对所描绘元素的评论/注释

这篇关于如何获取要插入到 DOM 中的 SVG 文档数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆