javascript - 如何在后端渲染 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"
}
}
解决方案
在 d3.js v6 中,d3.entries
替换为Object.entries
,如d3 6.0 迁移指南中所述。
在您的情况下,以下修改应该可以解决问题:
var data_ready = pie(Object.entries(data));
并且请让知道是否有任何其他选项可以使用节点 js 生成 svg 文件
要使用 d3 生成图表服务器端,它可能更容易使用d3-node
.
推荐阅读
- azure - Azure Functions 高级计划在不活动或部署后仍然有冷启动
- codeigniter - Codeigniter ALYWAS 404 的问题除索引页外未找到
- rundeck - 我们可以为 Rundeck 中的项目提供日志目录吗?
- php - 带有撇号问题的 Wordpress 字符编码
- ios - 使用 ekeventeditcontroller 在 ios 日历中创建事件不会向某些受邀者发送邮件
- mysql - NODE RED - 如何从 MQTT 获取 payload_raw 值并保存到 MySql
- javascript - 使用 Fabric.js 更改每次缩放的画布大小
- python - 在 Python 3.4.4 中不使用 panda 的情况下如何删除特定行?
- go - 包“fmt”运行时问题
- semantic-ui - 如何使日历反转颜色,或改变其他颜色特性?