如何使用jsDom – node.js来操作svg?
我有以下的svg
文件
FileName :
seatLayout.svg
<?xml version="1.0" encoding="utf-8"?> <!-- Generator: Adobe Illustrator 16.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="800px" height="600px" viewBox="0 0 800 600" enable-background="new 0 0 800 600" xml:space="preserve"> <g id="111"> <rect x="130" y= "130" height="320" width="550" id="rect1" fill ="white" stroke="blue" > </rect> </g> </svg>
注意
技术/编程 – node.js
我想追加rect
元素内的文本元素
<text x="0" y="10" font-family="Verdana" font-size="55" fill="blue" > Hello </text>
我曾试图使用jsDOM来实现。 但它不工作。
jsdom.env('seatLayout.svg', function (errors, window) { if(!errors){ console.log(window.document.getElementById("rect1")); } });
问题
它logging整个窗口对象而不是rect
元素。
是否有可能使用jsDOM操纵svg?
任何build议将不胜感激
希望你正在操纵你的rect1
的innerHTML
注意:正如Robert Longson所指出的那样,像<circle>
这样的SVG
标签不能是<rect>
的子元素,所以对于SVG
也需要考虑这些事情。 我不善于SVG
,但是下面是执行所需操作的Node.js代码。
Node.js代码:
var strSVG = '<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="800px" height="600px" viewBox="0 0 800 600" enable-background="new 0 0 800 600" xml:space="preserve"> <g id="111"> <rect x="130" y= "130" height="320" width="550" id="rect1" fill ="white" stroke="blue" > </rect> </g></svg>' var strYourText = 'Hello'; var jsdom = require("jsdom"); jsdom.env({ html : strSVG, done : function (errors, window) { window.document.getElementById("rect1").innerHTML = strYourText; console.log(window.document.getElementsByTagName('html')[0].innerHTML); } } );
更新:以下代码可用于生成有效的DOCTYPEstring。
var node = document.doctype; var html = "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>';
此方法返回有效(HTML5)文档types的正确string,例如:
-
<!DOCTYPE html>
-
<!DOCTYPE html SYSTEM "about:legacy-compat">
-
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
代码解释:
node.name # Holds the name of the root element, eg: HTML / html node.publicId # If this property is present, then it's a public document type. #>Prefix PUBLIC !node.publicId && node.systemId # If there's no publicId, but a systemId, prefix SYSTEM node.systemId # Append this if present