2017-06-14 11 views
0

我正在與d3一起工作,以便可視化力指向圖。如何在node.js中正確導入d3庫?

我開始使用cdn文件進行項目。但我發現一個問題,如果我用這個代碼:

https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js

..functions像d3.forceSimulation()是不可用的,至少它拋出一個錯誤。所以我改變了鏈接到這一個:

https://d3js.org/d3.v4.min.js

...根據這個例子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

我刪除了所有D3腳本從html

const d3 = require('d3') 
const d3SelectionMulti = require('d3-selection-multi') 

我也試過:

import * as d3 from 'd3' 
import 'd3-selection-multi' 

我根據文檔中使用.attrs代替.attrd3-selection-multi v1.0.1

這是它引發錯誤

我在我即文件中添加了此在那些變化之後:Uncaught TypeError: d3.select(...).append(...).attrs is not a function

+0

您是否正在使用插件來允許您僅使用一個'.attr({})'調用來分配屬性?如果'svg'在您執行此操作後爲空,則可能與此問題有關。嘗試控制檯日誌記錄'svg'(它可能未定義)在開始'let circle = ...'的行之前。如果註釋掉'.attr({...})'行,它還是未定義的嗎? – anbnyc

+0

@anbnyc我沒有使用任何插件。如果我評論'attr({...})'svg現在定義..你會推薦我什麼插件?謝謝 –

回答

1

D3.js v4破解了api的變化。你在版本煉獄。你需要放手v3並擁抱v4。

functions like d3.forceSimulation() are not available

因爲您試圖使用v3中不存在的v4函數。

But new problem came out: Uncaught TypeError: Cannot read property 'append' of null, that means, svg.

最有可能是因爲你試圖使用attr同一個對象,這V4不支持開箱即用。

你需要https://github.com/d3/d3-selection-multi

你的import語句是正確的。

+0

感謝您的幫助,但是我怎樣才能使用那些沒有這麼多的庫''節點中有沒有使用'require'的選項? –

+0

我想你只是在導入d3後執行'import'd3-selection-multi';'。它應該修改d3原型。 –

+0

謝謝。我會環顧四周。我不知道爲什麼它不起作用。我用最近的例子編輯了這個問題。再次感謝! –