首页 > 解决方案 > 如何在后端渲染 svg 并使用 d3 在节点 js 中保存到本地?

问题描述

当我尝试使用 d3js 绘制饼图并且错误 d3.entries is not a function 但我使用的是 d3js 6.5.0 版时。任何帮助将不胜感激。

并且请让知道是否有任何其他选项可以使用节点 js 生成 svg 文件并将其直接添加到 pdf 中。

const d3 = require("d3");
const fs = require("fs");
const { JSDOM } = require("jsdom");

// init d3 - https://gist.github.com/tomgp/c99a699587b5c5465228
const dom = new JSDOM(
  `<!DOCTYPE html><body><div id="my_dataviz"></div></body>`,
  { pretendToBeVisual: true }
);

let body = d3.select(dom.window.document.querySelector("#my_dataviz"));

// D3JS CODE * * * * * * * * * * * * * * * * * * * * * * * *

let width = 400;
let height = 400;
let marin = 60;
let radius = Math.min(width, height) / 2 - marin;

var svg = body.append("svg").attr("width", width).attr("height", height);

var data = { MacOS: 29, ios: 20, Windows: 30, Linux: 8, Android: 12 };

// set the color scale
var color = d3
  .scaleOrdinal()
  .domain(["MacOS", "ios", "Windows", "Linux", "Android"])
  .range(d3.schemeDark2);

var pie = d3
  .pie()
  .sort(null) // Do not sort group by size
  .value((data) => data.value);
var data_ready = pie(d3.entries(data));

svg
  .append("rect")
  .attr("id", "rect1")
  .attr("x", 10)
  .attr("y", 10)
  .attr("width", 80)
  .attr("height", 80)
  .style("fill", "green");
// END (D3JS) * * * * * * * * * * * * * * * * * * * * * * * *

console.log(body.html());

错误发生在:

var data_ready = pie(d3.entries(data))
                       

TypeError:d3.entries 不是函数

package.json 文件:

    {
      "name": "d3_charts",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "type": "module",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "repository": {
        "type": "git",
        "url": "git+https://github.com/SubhamSubhasisPatra/d3.git"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "bugs": {
        "url": "https://github.com/SubhamSubhasisPatra/d3/issues"
      },
      "homepage": "https://github.com/SubhamSubhasisPatra/d3#readme",
      "dependencies": {
        "d3": "^6.5.0",
        "jsdom": "^16.4.0",
        "d3-node": "^2.2.3",
        "pdfkit": "^0.12.3"
      }
    }

标签: javascriptnode.jsd3.jsjsdom

解决方案


在 d3.js v6 中,d3.entries替换为Object.entries,如d3 6.0 迁移指南中所述。

在您的情况下,以下修改应该可以解决问题:

var data_ready = pie(Object.entries(data));

并且请让知道是否有任何其他选项可以使用节点 js 生成 svg 文件

要使用 d3 生成图表服务器端,它可能更容易使用d3-node.


推荐阅读