javascript - 将 SVG 元素转换为 img
问题描述
没有一个相关的问题有答案。我想从 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>
推荐阅读
- linux - 如何在 Linux 服务器上安装 Mosquitto MQTT
- hive - HiveSQL IF ELSE STATMENT 条件从 GreenPlum 迁移
- wordpress - 如何通过.htaccess在单页上设置403 Forbidden
- pytorch - in_features 和 out_features 应该是什么?
- android - 在多语言 Android 应用程序中处理 TextView 中的混合语言文本
- geoserver - 带有 nodata 的 Geoserver WMTS 插件
- java - 使用 while 循环将值输入 Java 进程构建器并获取输出
- javascript - 如何排除空格作为用户输入?
- reactjs - React-final-form 焦点不关注给定字段
- swift - 如何在 swift 中将一侧的角半径提供给 Imageview?