Skip to content

Instantly share code, notes, and snippets.

@etpinard
Last active September 28, 2022 06:01
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save etpinard/58a9e054b9ca7c0ca4c39976fc8bbf8a to your computer and use it in GitHub Desktop.
Save etpinard/58a9e054b9ca7c0ca4c39976fc8bbf8a to your computer and use it in GitHub Desktop.
Generate plotly.js images (only svg for now) in Node.js using jsdom
"Generate plotly.js images (only svg for now) in Node.js using jsdom"
node_modules
package-lock.json

plotly.js-jsdom

Generate plotly.js images (only svg for now) in Node.js using jsdom.

How to run this thing

npm start

which outputs fig.svg

Future work

  • Try using the canvas npm package to support png and jpeg (and webp?) exports
  • Try to incorporate headless-gl into plotly.js to support exports for WebGL-based graphs
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
const fsPromises = require('fs').promises;
const jsdom = require('jsdom')
const pathToPlotly = require.resolve('plotly.js-dist')
const fig = { data: [{ y: [1, 2, 1] }] }
const opts = { format: 'svg', imageDataOnly: true }
const virtualConsole = new jsdom.VirtualConsole()
virtualConsole.sendTo(console)
const w = new jsdom.JSDOM('', { runScripts: 'dangerously', virtualConsole }).window
// mock a few things that JSDOM doesn't support out-of-the-box
w.HTMLCanvasElement.prototype.getContext = function() { return null; };
w.URL.createObjectURL = function() { return null; };
fsPromises.readFile(pathToPlotly, 'utf-8')
.then(w.eval)
.then(() => w.Plotly.toImage(fig, opts))
.then(img => fsPromises.writeFile('fig.svg', img))
.catch(console.warn)
{
"name": "plotly.js-jsdom",
"version": "1.0.0",
"description": "Generate plotly.js images (only svg for now) in Node.js using jsdom",
"main": "index.js",
"scripts": {
"start": "node main.ks"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"jsdom": "^13.1.0",
"plotly.js-dist": "^1.43.1"
},
"engines": {
"node": ">=10"
}
}
@jplox
Copy link

jplox commented Sep 28, 2022

@HuddleHouse the above code doesn't generate any png and any alternative work around .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment