相关的问题都没有答案。我想我的SVG从DOM画图,并将其转换为作为一个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')!
- 为什么?
作为一个良好的实践开放Inspector面板中,浏览器的控制台选项卡中看到错误消息。
长谈之后,我明白你的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>