-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
65 lines (55 loc) · 1.85 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const fs = require('fs');
const puppeteer = require('puppeteer');
function captureImage (html, { jpeg, quality, path, viewport, puppeteer_options }, callback) {
const screenShotOptions = { viewport, path, quality };
if (jpeg) {
screenShotOptions.type = 'jpeg'
}
return puppeteer.launch(puppeteer_options)
.then((browser) => {
browser.newPage()
.then((page) => {
page.setContent(html)
if (viewport) {
page.setViewport(viewport);
}
page.screenshot(screenShotOptions)
.then(() => browser.close())
.then(() => {
console.log('>> Exported:', screenShotOptions.path)
if (typeof callback === 'function') callback();
})
.catch(console.error);
})
})
.catch(console.error)
}
module.exports = function (dest, d3n, opts = {}, callback) {
const d3 = d3n.d3;
if (d3n.options.canvas) {
const canvas = d3n.options.canvas;
canvas.pngStream().pipe(fs.createWriteStream(`${dest}.png`));
console.log(`>> Exported canvas to ${dest}.png`);
return;
}
function eachGeoQuantize (d) {
const coords = d3.select(this).attr('d') || ''
const rounded = coords.replace(/[0-9]*\.[0-9]*/g, (x) => (+x).toFixed(4))
d3.select(this).attr('d', rounded);
}
// reduce filesize of svg
d3n.d3Element.selectAll('path').each(eachGeoQuantize);
const html = d3n.html()
const svgString = d3n.svgString();
fs.writeFile(`${dest}.html`, html, function () {
console.log(`>> Exported "${dest}.html", open in a web browser`)
});
fs.writeFile(`${dest}.svg`, svgString, function () {
console.log(`>> Exported "${dest}.svg"`);
});
const { width, height, jpeg, quality } = opts;
let viewport = false
if (width && height) viewport = { width, height }
const ext = jpeg ? 'jpg' : 'png'
captureImage(html, { jpeg, quality, path: `${dest}.${ext}`, viewport }, callback);
};