插件窝 干货文章 前端如何以编码形式显示后端返回的SVG图像?

前端如何以编码形式显示后端返回的SVG图像?

SVG 使用 setAttribute 标签 647    来源:    2025-03-19

在前端以编码形式显示后端返回的SVG图像,通常可以通过以下几种方式实现:

1. 使用 img 标签

如果后端返回的是SVG文件的URL,可以直接使用 img 标签来显示SVG图像。

<img src="path/to/your/svg/file.svg" alt="SVG Image">

2. 使用 object 标签

object 标签可以用来嵌入SVG文件,并且可以设置宽度和高度。

<object type="image/svg+xml" data="path/to/your/svg/file.svg" width="300" height="200">
  Your browser does not support SVG
</object>

3. 使用 iframe 标签

iframe 标签也可以用来嵌入SVG文件。

<iframe src="path/to/your/svg/file.svg" width="300" height="200">
  Your browser does not support iframes
</iframe>

4. 使用 embed 标签

embed 标签是另一种嵌入SVG文件的方式。

<embed src="path/to/your/svg/file.svg" type="image/svg+xml" width="300" height="200">

5. 使用 svg 标签直接嵌入

如果后端返回的是SVG的XML代码,可以直接将SVG代码嵌入到HTML中。

<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>

6. 使用 JavaScript 动态插入

如果后端返回的是SVG的XML代码,可以使用JavaScript动态插入到DOM中。

fetch('path/to/your/svg/file.svg')
  .then(response => response.text())
  .then(svg => {
    document.body.insertAdjacentHTML('beforeend', svg);
  });

7. 使用 Data URI

如果后端返回的是SVG的Base64编码,可以使用 Data URI 来显示SVG图像。

<img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIj48Y2lyY2xlIGN4PSI1MCIgY3k9IjUwIiByPSI0MCIgc3Ryb2tlPSJibGFjayIgc3Ryb2tlLXdpZHRoPSIzIiBmaWxsPSJyZWQiIC8+PC9zdmc+" alt="SVG Image">

8. 使用 XMLSerializer

如果后端返回的是SVG的DOM对象,可以使用 XMLSerializer 将其转换为字符串并插入到HTML中。

const svgElement = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svgElement.setAttribute('width', '100');
svgElement.setAttribute('height', '100');
const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
circle.setAttribute('cx', '50');
circle.setAttribute('cy', '50');
circle.setAttribute('r', '40');
circle.setAttribute('stroke', 'black');
circle.setAttribute('stroke-width', '3');
circle.setAttribute('fill', 'red');
svgElement.appendChild(circle);

const serializer = new XMLSerializer();
const svgString = serializer.serializeToString(svgElement);
document.body.insertAdjacentHTML('beforeend', svgString);

总结

根据后端返回的SVG数据格式(URL、XML代码、Base64编码等),可以选择不同的方式来在前端显示SVG图像。最常见的方式是使用 img 标签或直接嵌入SVG代码。