簡體   English   中英

如何在node.js中正確導入d3庫?

[英]How to import d3 library properly in node.js?

我正在使用d3 ,以便可視化力導向圖。

我使用CDN文件開始了我的項目。 但是,如果使用以下代碼,我發現了一個問題:

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

..d3.forceSimulation d3.forceSimulation()類的功能不可用,至少會引發錯誤。 因此,我將網址更改為以下網址:

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

...根據此示例力導向圖

但是出現了新問題: 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腳本。

我將此添加到我的viz文件中:

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

D3.js v4對API進行了重大更改。 您正在使用煉獄版。 您需要放開v3並擁抱v4。

d3.forceSimulation()之類的功能不可用

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

但是出現了新問題:Uncaught TypeError:無法讀取null的屬性“ append”,這意味着svg。

很有可能是因為您要嘗試將attr與某個對象一起使用,而v4不支持該功能。

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

您的導入聲明是正確的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM