我一直在尝试在Node.js中调用D3。我首先尝试使用脚本标签从D3的网站导入d3.v2.js,但是后来读到了这个帖子:
D3的作者建议应该'npm install d3'...我按照这个方法做了,并且我可以在node控制台成功调用它:
dpc@ananda:$ node
> var d3 = require("d3");
undefined
> d3.version;
'2.8.1'
然而,当我尝试从app.js中使用"node app.js"调用它时,我会得到以下错误信息:
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Cannot read property 'BSON' of undefined
at /Users/dpc/Dropbox/sync/Business/MindfulSound/Development/nad.am/nadam/node_modules/mongoose/node_modules/mongodb/lib/mongodb/index.js:45:44
我意识到在其他地方,D3的作者已经明确指出应该要求canvas:
https://github.com/mbostock/d3/blob/master/examples/node-canvas/us-counties.js
如下:
var Canvas = require("canvas");
但即使如此,(并且在app.js的require语句中特别要求使用index.js而不是d3.v2.js),我仍然无法在Jade模板中使下面的内容正常工作:
- script('/javascripts/d3.v2.js')
h1 Dashboard
section.css-table
section.two-column
section.cell
hr.grey
h2 Statistics
#mainGraph
script(type="text/javascript")
var Canvas = require("canvas");
var w = 400,
h = 400,
r = Math.min(w, h) / 2,
data = d3.range(10).map(Math.random).sort(d3.descending),
color = d3.scale.category20(),
arc = d3.svg.arc().outerRadius(r),
donut = d3.layout.pie();
var vis = d3.select("body").append("svg")
.data([data])
.attr("width", w)
.attr("height", h);
var arcs = vis.selectAll("g.arc")
.data(donut)
.enter().append("g")
.attr("class", "arc")
.attr("transform", "translate(" + r + "," + r + ")");
var paths = arcs.append("path")
.attr("fill", function(d, i) { return color(i); });
paths.transition()
.ease("bounce")
.duration(2000)
.attrTween("d", tweenPie);
paths.transition()
.ease("elastic")
.delay(function(d, i) { return 2000 + i * 50; })
.duration(750)
.attrTween("d", tweenDonut);
function tweenPie(b) {
b.innerRadius = 0;
var i = d3.interpolate({startAngle: 0, endAngle: 0}, b);
return function(t) {
return arc(i(t));
};
}
function tweenDonut(b) {
b.innerRadius = r * .6;
var i = d3.interpolate({innerRadius: 0}, b);
return function(t) {
return arc(i(t));
};
section.cell
hr.grey
h2 Achievements
npm install d3
加载 d3 节点模块,使你可以在服务器内存中构建数据驱动文档,然后将它们作为预先构建(渲染)的 html/svg 等传递到浏览器。与传统 d3 的用法相比,在 HTML 中包括库并在浏览器中呈现元素。客户端与服务器端呈现之间有微妙但重要的差异。参见:http://mango-is.com/blog/engineering/pre-render-d3-js-charts-at-server-side.html - Brad Hein