javascript - 将 SVG 元素转换为 img

标签 javascript html

所有相关问题都没有答案。 我想从 DOM 获取 SVG 绘图,并将其转换为 img。

这就是我的函数现在的样子

const SVG = document.querySelector('svg')!;
const canvas = document.createElement('canvas');

const XML = new XMLSerializer().serializeToString(SVG);
const SVG64 = btoa(XML);
const image64 = 'data:image/svg+xml;base64,' + SVG64;

const img = new Image();
img.onload = function() {
  canvas.getContext('2d')!.drawImage(img, 0, 0);
};

img.src = image64;

document.getElementById('container')!.appendChild(img);

和 DOM

<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50">
   <circle cx="25" cy="25" r="20" />
</svg>

<div id="container"></div>

结果是一张空白图像。它确实有一个 dataurl 作为 src,但完全空白。这是为什么?应该如何运作?

最佳答案

观察错误:

const SVG = document.querySelector('svg')!;
const XML = new XMLSerializer().serializeToString(SVG);
const SVG64 = btoa(XML);

const img = new Image();
img.height = 500;
img.width = 500;
img.src = 'data:image/svg+xml;base64,' + SVG64;

document.getElementById('container')!.appendChild(img);
SVG:<br/>
<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50">
   <circle cx="25" cy="25" r="20" />
</svg>

<hr/>

<div id="container" style="background: red;">
</div>

您似乎对 ! 标记有疑问: document.querySelector('svg')!, canvas.getContext('2d')!, document.getElementById('container')! - 为什么?

作为良好实践,打开检查器面板、浏览器的控制台选项卡以查看错误消息。

经过长时间的交谈,我了解到您的js代码位于html元素之上。

所以尝试在窗口加载后进行渲染。

检查一下:

window.onload = function() {
  renderSVG();
}

const renderSVG = function() {
  const container = document.getElementById('container');
  const svg = document.querySelector('svg');

  if (container && svg) { // since You want to check existence of elements
    const XML = new XMLSerializer().serializeToString(svg);
    const SVG64 = btoa(XML);

    const img = new Image();
    img.height = 500;
    img.width = 500;
    img.src = 'data:image/svg+xml;base64,' + SVG64;

    container.appendChild(img);
  }
};
SVG:<br/>
<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50">
   <circle cx="25" cy="25" r="20" />
</svg>

<hr/>

<div id="container" style="background: red;">
</div>

关于javascript - 将 SVG 元素转换为 img,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54535222/

相关文章:

javascript - 无法使用 jQuery AJAX 从服务器获取孟加拉语语言的数据

javascript - 将图像更改为内联 SVG >> 以获得所有 SVG 功能

javascript - 在某些情况下数组未填充

javascript - 防止 Jade 在 HTML 元素中添加赋值子句

html - Bootstrap 侧边栏高度不正确

php - 如何关闭动态组中的div?

javascript - 用于匹配重音字符的正则表达式

html - 在一个内部填充两个动态 div

javascript - 迭代数组内的数组并显示playerId、playerName和playerCategory

html - 带面具的 svg 在 chrome 上看不到