如何在 Nodejs 中使用 Observable Plot?

编程入门 行业动态 更新时间:2024-10-05 15:35:39

<a href=https://www.elefans.com/category/jswz/34/1771448.html style=如何在 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?

本文发布于:2024-05-30 12:46:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770511.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   Nodejs   Plot   Observable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!