javascript 有没有办法将 JSON 转换为 SVG 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17455436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to convert JSON to an SVG object?
提问by rkingrum
I'm working on a signature capture applet and one of the requirements is that it stores the signature as an SVG for future use. I am currently using Signature Padto capture the signature, but it stores it as JSON. Is there anyway to generate an SVG object using JSON, or am I going about this the wrong way?
我正在开发一个签名捕获小程序,其中一个要求是它将签名存储为 SVG 以备将来使用。我目前正在使用Signature Pad来捕获签名,但它将其存储为 JSON。有没有办法使用 JSON 生成一个 SVG 对象,或者我是否以错误的方式处理这个问题?
回答by Oliver
Thankfully Signature Pad encodes the JSON data in a super readable way. Because SVG is just a text document, we can easily programmatically generate an SVG image given the encoded JSON signature.
值得庆幸的是,Signature Pad 以一种超级可读的方式对 JSON 数据进行编码。因为 SVG 只是一个文本文档,我们可以通过编码的 JSON 签名轻松地以编程方式生成 SVG 图像。
As a proof-of-concept, take this regenerated signaturefrom the Pad docs. We just need to generate SVG paths from each object. Looking at the sourcefor how it's done for canvas (search for drawSignature
), you can make a simple example in whatever language you choose.
作为概念验证,从 Pad 文档中获取这个重新生成的签名。我们只需要从每个对象生成 SVG 路径。查看有关如何为画布完成的源代码(搜索drawSignature
),您可以使用您选择的任何语言制作一个简单的示例。
Here's a jsfiddle for it in JavaScript.
function generate_svg(paths) {
var svg = '';
svg += '<svg width="198px" height="55px" version="1.1" xmlns="http://www.w3.org/2000/svg">\n';
for(var i in paths) {
var path = '';
path += 'M' + paths[i].mx + ' ' + paths[i].my; // moveTo
path += ' L ' + paths[i].lx + ' ' + paths[i].ly; // lineTo
path += ' Z'; // closePath
svg += '<path d="' + path + '"stroke="blue" stroke-width="2"/>\n';
}
svg += '</svg>\n';
return svg;
}