【问题标题】:Remove HTML, HEAD and BODY Tags for fetching SVG移除 HTML、HEAD 和 BODY 标签以获取 SVG
【发布时间】:2021-09-18 13:12:45
【问题描述】:

我正在尝试从链接中获取 SVG 图像。从https://www.coingecko.com/coins/976/sparkline 获取 svg 图像时,它工作得很好,svg 图像被显示。当我尝试从 https://www.coinparticle.com/sparkline/bitcoin 获取它时,它不会显示。

我认为这与 HTML 代码中使用的某些标签有关。

<html>
<head></head>
<body></body>
</html>

如何调整 coinparticle 上的代码以获取 svg 图像(我可以访问 coinparticle 服务器)?

1
<img class="1" src="https://www.coingecko.com/coins/7598/sparkline">

2
<img class="2" src="https://www.coinparticle.com/sparkline/bitcoin">

coinparticle 上的代码:

<html></html>

<script>

  const height = 50; //the number of pixels high the chart is to be
  const points = [[1631264425426,46187.88927989531],[1631268120084,46346.477413458255],[1631271810755,46460.52411265284],[1631275266134,46472.58450929567]]

  const len = points.length;
  let minx = points[0][0]
  let maxx = points[0][0];
  let miny = points[0][1];
  let maxy = points[0][1];

  points.forEach( (point) => {
    minx = (point[0] < minx) ? point[0] : minx;
    maxx = (point[0] > maxx) ? point[0] : maxx;
    miny = (point[1] < miny) ? point[1] : miny;
    maxy = (point[1] > maxy) ? point[1] : maxy;
  } );

  function setup() {
    const width = 135;
    let svg = '<svg width="' + width +  '" height="' + (height+4) + '" viewBox="0 0 135 54"' + '"xmlns="http://www.w3.org/2000/svg"' + '"xmlns:xlink="http://www.w3.org/1999/xlink"' + '><polyline points="';

    points.forEach( (point) => {
      svg = svg + ((point[0] - minx) / (maxx - minx)) * width + ',' + (height - ((point[1] - miny) / (maxy - miny)) * height + 2) + ' ';
    });
    svg = svg + '" stroke-linejoin="round" style="fill: transparent; stroke:green; stroke-width:2" /></svg>';

    document.body.insertAdjacentHTML('beforebegin', svg)

  }
  setup();

</script>

【问题讨论】:

  • @RobertLongson 嗨 Robbert 我已经尝试过了,但它似乎不起作用。你觉得跟标签有关系吗?
  • @RobertLongson 非常感谢您的建议。我添加了一个工作原型。希望这就是您正在寻找的。​​span>
  • 图像无法运行脚本,因此当您编写&lt;img class="2" src="https://www.coinparticle.com/sparkline/bitcoin"&gt; 时,https://www.coinparticle.com/sparkline/bitcoin 中的任何脚本都不会运行
  • @RobertLongson 好吧。那么我该如何解决呢?我想从数据集中创建一个 svg 图像并获取该图像。我该怎么办? (我使用nodejs作为后端)
  • 不要使用 img 标签。 iframe 和 object 标签都允许它们的内容运行脚本。

标签: javascript html svg


【解决方案1】:

如果您不想更改 coinparticle 上的代码,您可以改为创建一个小的 iframe 来加载内容。

1
<img class="1" src="https://www.coingecko.com/coins/7598/sparkline">

2
<iframe src="https://www.coinparticle.com/sparkline/bitcoin" width="135" height="54" scrolling="no" style="border:0;overflow:hidden;"></iframe>

【讨论】:

  • 完美!如果我想更改代码我应该怎么做?使用 iframe 而不是 img 的主要缺点是什么,是加载时间吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-12
  • 2013-01-27
  • 1970-01-01
  • 2018-09-25
  • 2014-10-01
  • 2016-05-06
  • 1970-01-01
相关资源
最近更新 更多