我正在尝试根据以下教程将 d3 svg 图像转换为图像:https://github.com/hugolpz/svgcreator.node.js
我安装了以下语句:
sudo npm install -g jsdom d3js
npm install jsdom d3js
node svgcreator.node.js > out.svg
我使用了以下代码
var jsdom = require('jsdom');
jsdom.env(
"<html><body></body></html>", // CREATE DOM HOOK
[ 'http://d3js.org/d3.v3.min.js', // JS DEPENDENCIES online ...
'js/d3.v3.min.js' ], // ... & local-offline
function (err, window) {
// D3JS CODE * * * * * * * * * * * * * * * * * * * * * * * *
var svg = window.d3.select("body")
.append("svg")
.attr("width", 100)
.attr("height", 100);
svg.append("rect")
.attr("id", "rect1")
.attr("x", 10)
.attr("y", 10)
.attr("width", 80)
.attr("height", 80)
.style("fill", "green");
// END (D3JS) * * * * * * * * * * * * * * * * * * * * * * * *
//PRINTING OUT SELECTION
console.log( window.d3.select("body").html() );
} // end function
);
当我执行node svgcreator.node.js > out.svg时,我收到以下错误
TypeError: jsdom.env is not a function
at Object.<anonymous> (C:\Users\ErikvanderHoeven\Documents\git\svgcreator.node.js\svgcreator.node.js:5:7)
?[90m at Module._compile (internal/modules/cjs/loader.js:1063:30)?[39m
?[90m at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)?[39m
?[90m at Module.load (internal/modules/cjs/loader.js:928:32)?[39m
?[90m at Function.Module._load (internal/modules/cjs/loader.js:769:14)?[39m
?[90m at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)?[39m
?[90m at internal/main/run_main_module.js:17:47?[39
最佳答案
您似乎遇到了依赖项版本问题 - Github 项目中的代码已有几年历史,并且说明加载的依赖项版本比编写示例代码时要晚得多。
我在尝试安装 d3js
时遇到 npm 错误,并且 jsdom
版本为 v16.4。如果我运行:
npm install jsdom d3 --save
我的package.json
是:
{
"name": "test-jsdom",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"d3": "^6.5.0",
"jsdom": "^16.4.0"
}
}
Github用户dam1r89在此 gist 中展示了一种执行您在更高版本中尝试的操作的方法.
我的看法:
const d3 = require("d3");
const fs = require("fs");
const {JSDOM} = require("jsdom");
// init d3 - https://gist.github.com/tomgp/c99a699587b5c5465228
const minHtml = "<html><head></head><body></body></html>";
const dom = new JSDOM(`${minHtml}`, { pretendToBeVisual: true });
const window = dom.window;
window.d3 = d3.select(window.document);
// D3JS CODE * * * * * * * * * * * * * * * * * * * * * * * *
var svg = window.d3.select("body")
.append("svg")
.attr("width", 100)
.attr("height", 100);
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( window.d3.select("body").html() );
哪些输出:
<svg width="100" height="100"><rect id="rect1" x="10" y="10" width="80" height="80" style="fill: green;"></rect></svg>
关于node.js - jsdom.env 不是将 svg 导出到图像的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66215608/