简体   繁体   English

如何打印由javascript生成的svg代码?

[英]How to print svg code generated by javascript?

I have a javascript function that creates a svg in the body of the HTML page. 我有一个JavaScript函数,可在HTML页面的主体中创建一个svg。 Additionnaly to the creation of the webpage, I would like to extract the svg code generated by the javascript (the one between <svg>..</svg> ) and print it in a file to be past in an other document. 除了创建网页之外,我还要提取由javascript生成的svg代码(在<svg>..</svg>之间的代码)并将其打印在文件中,以便粘贴到其他文档中。

For example the following html: 例如以下html:

<html>
<head>
  <script>
    function CreateSVG () {
      var xmlns = "http://www.w3.org/2000/svg";
      var boxWidth = 300;
      var boxHeight = 300;
      var svgElem = document.createElementNS (xmlns, "svg");
      svgElem.setAttributeNS (null, "width", boxWidth);

      var g = document.createElementNS (xmlns, "g");
      svgElem.appendChild (g);
      g.setAttributeNS (null, 'transform', 'matrix(1,0,0,-1,0,300)');

      // draw borders
      var coords = "M 0, 0";
      coords += " l 0, 300";
      coords += " l 300, 0";
      coords += " l 0, -300";
      coords += " l -300, 0";

      var path = document.createElementNS (xmlns, "path");
      path.setAttributeNS (null, 'd', coords);
      g.appendChild (path);

      var svgContainer = document.getElementById ("svgContainer");
      svgContainer.appendChild (svgElem);
    }
  </script>
</head>

<body onload="CreateSVG ()">
  <div id="svgContainer"></div>
</body>
</html>

generates the following code (after being analysed by the web browser) : 生成以下代码(经过网络浏览器分析后):

<html> == $0
  <head> ... </head>
  <body onload="CreateSVG ()">
    <div id="svgContainer">
      <svg width ="300">
        <g transform="matrix(1,0,0,-1,0,300)">
          <path d="M 0, 0 1 0, 300 1 300, 0 1 0, -300 1 -300, 0"></path>
        </g>
      </svg>
    </div>
  </body>
</html>

How can I extract the <svg>...</svg> part to print it in an external file ? 如何提取<svg>...</svg>部分以将其打印在外部文件中?

Like Sujit Agarwal answered in https://stackoverflow.com/a/21012689/6869524 , one should 就像Sujit Agarwal在https://stackoverflow.com/a/21012689/6869524中回答的那样,应该

save it on your server then simply pass on the text data to your server and execute the file writing code using some server side language. 将其保存在服务器上,然后简单地将文本数据传递到服务器,并使用某种服务器端语言执行文件编写代码。

And the text is retreived using code = svgContainer.innerHTML 然后使用code = svgContainer.innerHTML检索文本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM