如何在 Nodejs 中使用 Observable Plot?"/>
如何在 Nodejs 中使用 Observable Plot?
我读到使用jsdom对于Observable Plot(从D3js派生的模块)在Nodejs中工作是必要的。
但是,关于这个的例子很少,我无法正确调整我找到的那些。
这是我试图改编的代码:
import * as Plot from "@observablehq/plot";
import jsdom from "jsdom";
const { JSDOM } = jsdom;
const sales = [
{units: 10, fruit: "fig"},
{units: 20, fruit: "date"},
{units: 40, fruit: "plum"},
{units: 30, fruit: "plum"}
];
Plot.dot(sales, {x: "units", y: "fruit"}).plot();
我尝试了不同的东西,比如添加:
import {select} from "d3-selection";
Plot.select(JSDOM.window.document.body).dot(sales, {x: "units", y: "fruit"}).plot();
试图重现为 d3 所做的事情here.
我也看到了this,里面可能有答案,但是对于我这样的javascript初学者来说,这是无法理解的
我应该如何调整我的代码?
回答如下:我终于可以这样得到我想要的了:
import http from 'http';
import * as Plot from "@observablehq/plot";
import {JSDOM} from "jsdom";
const jsdom = new JSDOM(`
<!DOCTYPE html>
<head><meta charset="UTF-8"></head>
<body><div class='container'><figure id='graphic'>
</figure></div></body>`);
const sales = [
{units: 10, fruit: "fig"},
{units: 20, fruit: "date"},
{units: 40, fruit: "plum"},
{units: 30, fruit: "plum"}
];
jsdom.window.document.getElementById('graphic')
.appendChild(Plot.dot(sales, {x: "units", y: "fruit"})
.plot({document: jsdom.window.document})
);
http.createServer(function (req, res) {
let html = jsdom.serialize();
res.end(html);
}).listen(8080);
jsdom 对象不需要随机创建,我在 jsdom 中使用 Plot.dot 的方式不正确。我还必须使用 http 模块在浏览器中呈现图形,并在 localhost:8080/.
访问它更多推荐
如何在 Nodejs 中使用 Observable Plot?
发布评论