【发布时间】:2017-06-14 21:17:46
【问题描述】:
我正在使用d3 来可视化力导向图。
我使用 cdn 文件开始了我的项目。但是我发现了一个问题,如果我使用这段代码:
..d3.forceSimulation() 之类的函数不可用,至少它会引发错误。所以我把网址改成了这个:
...根据这个例子Force-Directed Graph
但是又出现了新问题:Uncaught TypeError: Cannot read property 'append' of null,也就是说,svg。
我尝试使用npm 安装d3。于是我导入了d3:
import * as d3 from 'd3'
但是,我不知道如何将 svg 附加到 div
这是我发生错误时的代码:
图形/index.js
// import modules
import * as d3 from 'd3'
// export function
const force_graph = (w, h) => {
let svg = d3.select('#Gforce')
.append('svg')
.attr({
'width': w,
'height': h,
'cursor': 'default'
})
let circle = svg.append('circle')
.attr({
'cx': 325,
'cy': 270,
'r': 10,
'fill': '#7A6464',
'class': 'dot'
})
}
module.exports = force_graph
index.js
const graph = require('./graphic')
let w = document.getElementById('Gforce').offsetWidth
let h = document.getElementById('Gforce').offsetHeight
graph(w, h)
如何正确导入 d3 库。我尝试了这些选项,但我无法得到任何结果。我做错了什么?
编辑 1
我从html 中删除了所有 d3 脚本。
我在我的可视化文件中添加了这个:
const d3 = require('d3')
const d3SelectionMulti = require('d3-selection-multi')
我也试过了:
import * as d3 from 'd3'
import 'd3-selection-multi'
根据文档,我使用.attrs 代替.attr:d3-selection-multi v1.0.1
这是它在进行这些更改后引发的错误:Uncaught TypeError: d3.select(...).append(...).attrs is not a function
【问题讨论】:
-
您是否使用插件来允许您通过一个
.attr({})调用来分配属性?如果在你这样做之后svg为空,则可能与问题有关。在以let circle=...开头的行之前尝试控制台记录svg(可能未定义)。如果您注释掉.attr({...})行,它仍然未定义吗? -
@anbnyc 我没有使用任何插件。如果我评论
attr({...})svg 现在定义了.. 你会推荐我什么插件?谢谢
标签: javascript node.js d3.js