gpt4 book ai didi

javascript - 上传 React 渲染的 SVG

转载 作者:行者123 更新时间:2023-12-03 04:11:27 25 4
gpt4 key购买 nike

在我的应用程序中,用户可以在 SVG 中制作一些小图画,我使用 React 进行渲染。我想将 SVG 上传到我的服务器。

如何将 SVG 渲染为 Javascript 图像,以便将其上传到我的服务器? Google 搜索不会返回有意义的结果。

最佳答案

这不是特定于 react ,而是转换文档 <svg> 中的对于 svg 文件,您只需将其标记序列化为字符串(参见 XMLSerializer )并将生成的字符串附加到 Blob 中,然后将 Blob 上传到您的服务器。

但是如果您想要一个完整的独立 svg 文档,带有 doctype 和命名空间,这里有一个如何做到这一点的示例:

function svgNodeToBlob(node) {
// first an doctype
var svgDocType = document.implementation.createDocumentType('svg', "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd");
// then a new SVG Document
var svgDoc = document.implementation.createDocument('http://www.w3.org/2000/svg', 'svg', svgDocType);
// set its documentElement to our root svg node (well a clone of it)
svgDoc.replaceChild(node.cloneNode(true), svgDoc.documentElement);
// serialize the document
var svgData = (new XMLSerializer()).serializeToString(svgDoc);
// convert to a blob
var blob = new Blob([svgData], {
type: 'image/svg+xml; charset=utf8'
});
return blob;
}

var blob = svgNodeToBlob(document.querySelector('svg'));
// from here you can send the blob to your server

// for the demo, we'll just make an downloadable link from it
var a = document.querySelector('a');
a.href = URL.createObjectURL(blob);
a.download = 'mycoolsvgfile.svg';
<svg>
<rect width="50" height="50" x="20" y="10"/>
</svg>
<a>download as file</a>

但请注意,对您的节点有影响的所有外部资源都不会影响该文件(即,如果您使用外部样式表中的 CSS 进行一些样式设置)。在这种情况下,您必须先将这些外部元素的克隆附加到克隆节点内,然后再将其附加到 SVG 文档。

关于javascript - 上传 React 渲染的 SVG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44319858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com