【问题标题】:How to use Observable Plot in Nodejs?如何在 Nodejs 中使用 jsdom 和 Observable Plot?
【发布时间】:2022-11-28 19:11:25
【问题描述】:

我读到使用jsdom在必要的可观察情节(来自 D3js 的派生模块)工作节点.

但是,关于这方面的例子很少,我无法正确调整我发现的例子。

这是我试图改编的代码:

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 初学者来说是无法理解的。

我应该如何调整我的代码?

【问题讨论】:

    标签: node.js jsdom observable-plot


    【解决方案1】:

    我终于能够像这样获得我想要的东西:

    import http from 'http';
    import * as Plot from "@observablehq/plot";
    import {JSDOM} from "jsdom";
    
    const jsdom = new JSDOM(`
    <!DOCTYPE html><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 对象需要较少地随机创建,我将 Plot.dot 与 jsdom 一起使用的方式不正确。我还必须使用 http 模块在浏览器中呈现图形,并通过 localhost:8080/ 访问它。

    剩下的唯一问题是由于某种原因units在渲染图中被写成units →,但这是另一个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-07
      • 2022-02-09
      • 1970-01-01
      • 1970-01-01
      • 2016-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多