D3js:如何生成独立的SVG文件? (Nodejs) [英] D3js: how to generate standalone SVG files? (Nodejs)

查看:94
本文介绍了D3js:如何生成独立的SVG文件? (Nodejs)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定D3js代码

function () {
    var svg = window.d3.select("body")
        .append("svg")
        .attr("width", 100)
        .attr("height", 100);

    svg.append("rect")
        .attr("x", 10)
        .attr("y", 10)
        .attr("width", 80)
        .attr("height", 80)
        .style("fill", "orange");
}

如何生成正确的独立* .svg文件D3js代码& Node.js?

推荐答案

Github存储库 svgcreator.node.js

Github repository svgcreator.node.js to try out.

D3根本不在乎什么实际生成你的SVG。创建只有SVG的主要问题是,你不能有Javascript,那当然意味着你不能使用D3。除了这个基本的no-no,没有什么阻止你:)

D3 doesn't care at all what actually generate your SVG. The main problem with creating only SVG is that you can't have Javascript then, which of course means that you can't use D3. Apart from this fundamental no-no, there's nothing stopping you :)

概念证明灵感来自另一个答案,使用 jsdom 进行概念验证。

Proof of concept: Inspired by the other answer, here's some proof-of-concept code using jsdom.

<强> 1。安装NodeJS( 1 )。

1. Install NodeJS (1).

curl http://npmjs.org/install.sh | sh       #this should work (not tested)

2。使用节点包管理器安装jsdom( 2 ):

2. Install jsdom using the Node Packages Manager (2):

$npm install jsdom

3。在一些jsdom代码中封装您的D3js代码,粘贴到jsdom.node.js文件

var jsdom = require('jsdom');

jsdom.env(
  "<html><body></body></html>",
  [ 'http://d3js.org/d3.v3.min.js' ],
  function (err, window) {
    var svg = window.d3.select("body")
        .append("svg")
        .attr("width", 100).attr("height", 100);

    svg.append("rect")
        .attr("x", 10)
        .attr("y", 10)
        .attr("width", 80)
        .attr("height", 80)
        .style("fill", "orange");
// PRINT OUT:
    console.log(window.d3.select("body").html());
//  fs.writeFileSync('out.svg', window.d3.select("body").html()); // or this
  }
);

4。在终端中运行

$node jsdom.node.js > test.svg

stdout输出是SVG,然后注入到test.svg文件中。工作完成。

The stdout output is the SVG, which is then injected into a test.svg file. Job done.

正如Gilly在评论中指出的,您可能需要jsdom版本3才能正常工作。

As Gilly points out in the comments, you may need version 3 of jsdom for this to work.

这篇关于D3js:如何生成独立的SVG文件? (Nodejs)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆